Python computes the root of function f (x) = 0

From , 5 Years ago, written in Python, viewed 83 times.
URL https://pastebin.vip/view/b8002139
  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

Reply to "Python computes the root of function f (x) = 0"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website