Files
CalWay_Python/159-5.py
2025-06-10 14:29:12 +08:00

61 lines
1.3 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 f1(x):
return x**2 + 10*math.cos(x)
def df1(x):
return 2*x - 10*math.sin(x)
def f2(x):
return 1 + math.atan(x) - x
def df2(x):
return 1/(1+x**2) - 1
# 牛顿方法求解方程
def NewtonSolve(fx, dfx, x0, err, N0):
count = 0
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
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
if __name__ == "__main__":
err = 1e-5
N0 = 100
x0 = 1.6
result,status = NewtonSolve(f1, df1, x0, err,N0)
if status == 1:
print(f"f1收敛 解为: {result}")
elif status == -1:
print("f1不收敛")
else:
print("f1导数为0无法收敛")
x0 = FindRootZone(f2, -5, 5, 0.01)
result, status = NewtonSolve(f2, df2, x0, err,N0)
if status == 1:
print(f"f2收敛 解为: {result}")
elif status == -1:
print("f2不收敛")
else:
print("f2导数为0无法收敛")