牛顿法解一元非线性方程的代码
时间: 2024-10-16 14:01:01 浏览: 26
牛顿法是一种迭代算法,用于近似求解一元函数的根。以下是使用Python编写的基本牛顿法求解非线性方程的简单代码:
```python
def newton_raphson(f, f_prime, x0, epsilon=1e-6):
"""
使用牛顿法求解非线性方程f(x) = 0的根
参数:
f - 目标函数
f_prime - f的导数
x0 - 初始猜测点
epsilon - 准确度阈值,默认为1e-6
返回:
根的估计值
"""
def iteration():
current_x = x0
while True:
x_next = current_x - f(current_x) / f_prime(current_x)
if abs(x_next - current_x) < epsilon:
return x_next
current_x = x_next
return iteration()
# 示例:求解方程x^2 - 5 = 0
f = lambda x: x**2 - 5
f_prime = lambda x: 2 * x
initial_guess = 3 # 可以任意选择一个初始点
solution = newton_raphson(f, f_prime, initial_guess)
print(f"Solution found: {solution}")
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)