Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
IDL 1.09 KB | None | 0 0
  1. #Joe Cross
  2. #Bisection method for finding x in f(x) such that f(x) == 0 +/- err_lim
  3. #Using fixed point concept of g(x) = f(x) - x
  4.  
  5. from math import *
  6.  
  7. def scrub(f):
  8.     nf=''
  9.     nums='0123456789'
  10.     for i in range(len(f)):
  11.         nf += f[i]
  12.         if f[i] in nums:
  13.             if (i+1 < len(f) and f[i+1] != '.' and f[i+1] not in nums
  14.                 and f[i-1] != '.' and f[i-1] not in nums):
  15.                     nf += '.0'
  16.             elif i+1 == len(f):
  17.                 nf +='.0'
  18.     return nf      
  19.  
  20. def funct(f):
  21.     f=scrub(f)
  22.     def v(x):
  23.         try:
  24.             x=float(x)
  25.             return eval(f)
  26.         except:
  27.             return f
  28.     return v
  29.  
  30. def bisection(f,a,b,lim=1E-16):
  31.     a=float(a); b=float(b); lim=float(lim)
  32.  
  33.     #Following line added to use fixed point concept
  34.     f += '-x'
  35.        
  36.     F=funct(f)
  37.     while abs(b-a) > 2.*lim:
  38.         m= .5*(b+a)
  39.         if F(a)*F(b) > 0:
  40.             raise OverflowError("f(a) and f(b) have the same sign!")
  41.         elif F(a)*F(m) < 0.: b=m
  42.         elif F(m)*F(b) < 0.: a=m
  43.         else: return m
  44.     return m
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement