35 lines
1.0 KiB
Python
35 lines
1.0 KiB
Python
#正割法计算方程
|
||
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,无法收敛") |