This commit is contained in:
lwj
2025-06-14 11:40:57 +08:00
parent b509f51ceb
commit 852ee942ef
5 changed files with 15 additions and 9 deletions

View File

@@ -1,6 +1,6 @@
import math
#原函数和导数改成题干的形式#####################
def f1(x):
return x**2 + 10*math.cos(x)
@@ -17,12 +17,14 @@ def df2(x):
# 牛顿方法求解方程
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
@@ -41,6 +43,7 @@ if __name__ == "__main__":
err = 1e-5
N0 = 100
#把初始值换成题干形式###############
x0 = 1.6
result,status = NewtonSolve(f1, df1, x0, err,N0)
if status == 1:
@@ -51,7 +54,7 @@ if __name__ == "__main__":
print("f1导数为0无法收敛")
x0 = FindRootZone(f2, -5, 5, 0.01)
x0 = FindRootZone(f2, -5, 5, 0.01) # 查找f2的根区间与步长
result, status = NewtonSolve(f2, df2, x0, err,N0)
if status == 1:
print(f"f2收敛 解为: {result}")