[Python] python计算函数 f(x) = 0的根 →→→→→进入此内容的聊天室

来自 , 2019-06-07, 写在 Python, 查看 132 次.
URL http://www.code666.cn/view/56c3b2c6
  1. ## module bisection
  2. ''' root = bisection(f,x1,x2,switch=0,tol=1.0e-9).
  3.    Finds a root of f(x) = 0 by bisection.
  4.    The root must be bracketed in (x1,x2).
  5.    Setting switch = 1 returns root = None if
  6.    f(x) increases upon bisection.
  7. '''    
  8. from math import log,ceil
  9. import error
  10.  
  11. def bisection(f,x1,x2,switch=1,tol=1.0e-9):
  12.     f1 = f(x1)
  13.     if f1 == 0.0: return x1
  14.     f2 = f(x2)
  15.     if f2 == 0.0: return x2
  16.     if f1*f2 > 0.0: error.err('Root is not bracketed')
  17.     n = ceil(log(abs(x2 - x1)/tol)/log(2.0))
  18.     for i in range(n):
  19.         x3 = 0.5*(x1 + x2); f3 = f(x3)
  20.         if (switch == 1) and (abs(f3) > abs(f1)) \
  21.                          and (abs(f3) > abs(f2)):
  22.             return None  
  23.         if f3 == 0.0: return x3
  24.         if f2*f3 < 0.0: x1 = x3; f1 = f3
  25.         else:           x2 = x3; f2 = f3
  26.     return (x1 + x2)/2.0
  27. #//python/7432

回复 "python计算函数 f(x) = 0的根"

这儿你可以回复上面这条便签

captcha