用递归算法完成牛顿迭代法,以方程e^x-x^2=0为例,对程序进行验证
# 定方程式e^x-x^2=0
# 设x0为初始值,x1为迭代值
x0 = 1
x1 = x0
# 迭代误差atol及最大迭代次数max_iter
atol = 1e-6
max_iter = 100
# 定义递归函数Newton
def Newton(x1):
# 迭代次数计数
n = 0
# 循环迭代
while n < max_iter:
# 计算方程的导数,斜率为e^x-2x
slope = np.exp(x1) - 2*x1
# 根据x = x0 - f(x0)/f'(x0)更新x值
x1 = x1 - (np.exp(x1) - x1**2) / slope
# 判断是否达到atol,是则跳出循环
if abs(np.exp(x1) - x1**2) < atol:
break
# 迭代次数加1
n += 1
# 检验最大迭代次数,并输出结果
if n == max_iter:
print('Fail to converge in ', max_iter, 'iterations.')
else:
print('The solution is: ', x1)
# 调用递归函数Newton
Newton(x0)
这个程序使用递归实现了牛顿迭代法,来求解方程e^x-x^2=0。主要步骤为:
望采纳!
def newton(x, f, df):
fx = f(x)
if abs(fx) < 1e-6:
return x
else:
x_next = x - fx / df(x)
return newton(x_next, f, df)
def f(x):
return math.exp(x) - x**2
def df(x):
return math.exp(x) - 2*x
root = newton(1.0, f, df)
print(root)