Files
CalWay_Python/159-1.py
2025-06-14 10:20:04 +08:00

26 lines
645 B
Python

#原函数换成题干的*********************
def fx(x):
return x**4-3*x+1
# 二分法求解方程的根
def SolveByDivTwo(x1,x2,err):
count = 1
while abs(x2-x1) >= err:
x = (x1+x2)/2
print(f"k={count},a{count}={x1},b{count}={x2},x{count}={x},fx(x)={fx(x)}")
if fx(x) * fx(x1) < 0:
x2 = x
else:
x1 = x
count += 1
return (x1+x2)/2
#范围和精度要求换成题干的############
if __name__ == "__main__":
x1 = 0.3
x2 = 0.4
err = 0.5e-5 #精度要求##################
root = SolveByDivTwo(x1, x2, err)
print(f"Root: {root:.5f}")