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

38 lines
1.2 KiB
Python
Raw Permalink 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 SecantSolve(fx, x0, x1, err=1e-10, N0=100):
count = 0
print(f"k={count}: x{count}={x0}, f(x{count})={fx(x0)}")
count += 1
print(f"k={count}: x{count}={x1}, f(x{count})={fx(x1)}")
count += 1
while abs(x1 - x0) > err or abs(fx(x1)) > err:
if fx(x1) == fx(x0):
return None,0
x2 = x1 - fx(x1) * (x1 - x0) / (fx(x1) - fx(x0))
print(f"k={count}: x{count}={x2}, f(x{count})={fx(x2)}")
count += 1
if count > N0:
return None,-1
x0 = x1
x1 = x2
return x2,1
if __name__ == "__main__":
##############################################################################################################
err = 1e-5 # 根的误差限 P148
N0 = 100 # 最大迭代次数
x0 = 0.3 # 初始值1
x1 = 0.4 # 初始值2
fx = lambda x: x**4 - 3*x + 1 #原函数
result, status = SecantSolve(fx, x0, x1, err, N0)
if status == 1:
print(f"fx收敛 解为: {result}")
elif status == -1:
print("fx不收敛")
else:
print("分母为0无法收敛")