Files
CalWay_Python/按方法整理/非线性方程-牛顿法.py
2025-06-16 20:44:29 +08:00

51 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import math
# 牛顿方法求解方程
def NewtonSolve(fx, dfx, x0, err, N0):
count = 0
print(f"k={count}, x0={x0}")
x1 = x0 + 1 + err
while abs(x1 - x0) > err or abs(fx(x1)) > err: # 添加条件修正根误差太大的问题
if abs(dfx(x1)) < 1e-10:
return None, 0
x1 = x0 - fx(x0) / dfx(x0)
count += 1
print(f"k={count}, x{count}={x1},x1-x0={abs(x1-x0)}")
if count > N0:
return None, -1
x0 = x1
return x1, 1
# 查找根区间
def FindRootZone(fx,start,stop,step):
x = start
while x < stop:
if fx(x) * fx(x+step) < 0:
return x
x += step
return None
# 定义原函数 ###############################
def fx(x):
return x**2 + 10*math.cos(x)
# 定义其导函数 ###############################
def dfx(x):
return 2*x - 10*math.sin(x)
if __name__ == "__main__":
##############################################################################################################
err = 1e-5 # 根的误差限 见P141
N0 = 100 # 最大迭代次数
x0 = 1.6 # 可以指定初始值
# x0 = FindRootZone(fx, 0, 2, 0.1) # 也可以用找根函数给定范围找根的缩小范围
result,status = NewtonSolve(fx, dfx, x0, err,N0)
if status == 1:
print(f"fx收敛 解为: {result}")
elif status == -1:
print("fx不收敛")
else:
print("fx导数为0无法收敛")