You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
def newton_method(f, f_prime, x0, tol=1e-6, max_iter=100):
|
|
|
|
|
"""
|
|
|
|
|
牛顿迭代法计算函数值为0的解
|
|
|
|
|
|
|
|
|
|
参数:
|
|
|
|
|
- f: 要求解的函数
|
|
|
|
|
- f_prime: 函数的导数
|
|
|
|
|
- x0: 初始猜测值
|
|
|
|
|
- tol: 容差(迭代停止的条件,可选,默认为1e-6)
|
|
|
|
|
- max_iter: 最大迭代次数(可选,默认为100)
|
|
|
|
|
|
|
|
|
|
返回:
|
|
|
|
|
- 解的近似值
|
|
|
|
|
"""
|
|
|
|
|
x = x0 # 初始猜测值
|
|
|
|
|
for _ in range(max_iter):
|
|
|
|
|
fx = f(x) # 函数值
|
|
|
|
|
if abs(fx) < tol:
|
|
|
|
|
# 已达到容差要求,返回解的近似值
|
|
|
|
|
return x
|
|
|
|
|
fpx = f_prime(x) # 函数的导数值
|
|
|
|
|
if abs(fpx) < tol:
|
|
|
|
|
# 导数值过小,无法继续迭代
|
|
|
|
|
break
|
|
|
|
|
x -= fx / fpx # 牛顿迭代公式
|
|
|
|
|
# 迭代未收敛或超过最大迭代次数,返回None表示未找到解
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
def f(x):
|
|
|
|
|
return x**2 - 4
|
|
|
|
|
|
|
|
|
|
def f_prime(x):
|
|
|
|
|
return 2 * x
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
|
x0 = 1 # 初始猜测值
|
|
|
|
|
solution = newton_method(f, f_prime, x0)
|
|
|
|
|
print("解的近似值:", solution)
|