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

29 lines
777 B
Python

import math
# 二分法求解方程的根
def SolveByDivTwo(x1,x2,fx,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
# 原函数换成题干的 #############################
def fx(x):
return x**4-3*x+1
if __name__ == "__main__":
##############################################################################################################
x1 = 0.3 # x下限范围
x2 = 0.4 # x上限范围
err = 0.5e-5 # 精度要求 P125
root = SolveByDivTwo(x1, x2,fx,err)
print(f"Root: {root}")