Files
CalWay_Python/160-11.py
2025-06-14 11:40:57 +08:00

35 lines
1.0 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.

#正割法计算方程
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
N0 = 100
##把初始函数和初始值改成题干要求的##########################
x0 = 0.3
x1 = 0.4
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无法收敛")