Python find root of function f (x) =0

From , 4 Years ago, written in Python, viewed 54 times.
URL https://pastebin.vip/view/92dfa194
  1. ''' root = ridder(f,a,b,tol=1.0e-9).
  2.    Finds a root of f(x) = 0 with Ridder's method.
  3.    The root must be bracketed in (a,b).
  4. '''
  5. import error
  6. from math import sqrt
  7.  
  8. def ridder(f,a,b,tol=1.0e-9):  
  9.     fa = f(a)
  10.     if fa == 0.0: return a
  11.     fb = f(b)
  12.     if fb == 0.0: return b
  13.     if fa*fb > 0.0: error.err('Root is not bracketed')
  14.     for i in range(30):
  15.       # Compute the improved root x from Ridder's formula
  16.         c = 0.5*(a + b); fc = f(c)
  17.         s = sqrt(fc**2 - fa*fb)
  18.         if s == 0.0: return None
  19.         dx = (c - a)*fc/s
  20.         if (fa - fb) < 0.0: dx = -dx
  21.         x = c + dx; fx = f(x)
  22.       # Test for convergence
  23.         if i > 0:
  24.             if abs(x - xOld) < tol*max(abs(x),1.0): return x
  25.         xOld = x
  26.       # Re-bracket the root as tightly as possible
  27.         if fc*fx > 0.0:
  28.             if fa*fx < 0.0: b = x; fb = fx
  29.             else:           a = x; fa = fx
  30.         else:
  31.             a = c; b = x; fa = fc; fb = fx
  32.     return None
  33.     print 'Too many iterations'
  34. #//python/7401

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

Here you can reply to the paste above

captcha

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