python 二分法求方程的根

Python015

python 二分法求方程的根,第1张

import matplotlib.pyplot as plt

a=3

b=-2

x=(a+b)/2.0 # 中点

def f(x): # 定义方程

y=x-2**0.5

return(y)

u=max([a,b])

l=min([a,b])

i=0

z=[]

est=[]

# 循环体

while abs(f(x))>10.0**(-15.0): # 计算精度

if f(u)*f(l)>0: # 判断输入假设是否成立

print('Error: Assumption not holds! ')

break

if f(x)*f(u)>0: # 判断零点落入区间

u=x

x=(x+l)/2.0

else:

l=x

x=(x+u)/2.0

i=i+1

z=z+[abs(x-2**0.5)]

est=est+[abs(a-b)/2**i]

plt.semilogy(z)

plt.semilogy(est)

plt.grid('on')

plt.legend(['simu','theo'])

plt.show()

import math

def erfenfa(function, a, b): #定义函数,利用二分法求方程的根,function为具体方程,a,b为根的取值范围

 start = a

 end = b

 if function(a) == 0: 

  return a

 elif function(b) == 0:

  return b

 elif function(a) * function(b) >0: 

  print("couldn't find root in [a,b]")

  return

 else:

  mid = (start + end) / 2

  while abs(start - mid) >0.0000001: 

   if function(mid) == 0:

    return mid

   elif function(mid) * function(start) <0:

    end = mid

   else:

    start = mid

   mid = (start + end) / 2

  return mid

def f(x):#定义构造方程式函数

 return math.pow(x, 5) -15*math.pow(x, 4) +85*math.pow(x, 3)-225*pow(x,2)+274*x - 121

print(round(erfenfa(f, 1.5, 2.4),6))