Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #Joe Cross
- #Bisection method for finding x in f(x) such that f(x) == 0 +/- err_lim
- #Using fixed point concept of g(x) = f(x) - x
- from math import *
- def scrub(f):
- nf=''
- nums='0123456789'
- for i in range(len(f)):
- nf += f[i]
- if f[i] in nums:
- if (i+1 < len(f) and f[i+1] != '.' and f[i+1] not in nums
- and f[i-1] != '.' and f[i-1] not in nums):
- nf += '.0'
- elif i+1 == len(f):
- nf +='.0'
- return nf
- def funct(f):
- f=scrub(f)
- def v(x):
- try:
- x=float(x)
- return eval(f)
- except:
- return f
- return v
- def bisection(f,a,b,lim=1E-16):
- a=float(a); b=float(b); lim=float(lim)
- #Following line added to use fixed point concept
- f += '-x'
- F=funct(f)
- while abs(b-a) > 2.*lim:
- m= .5*(b+a)
- if F(a)*F(b) > 0:
- raise OverflowError("f(a) and f(b) have the same sign!")
- elif F(a)*F(m) < 0.: b=m
- elif F(m)*F(b) < 0.: a=m
- else: return m
- return m
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement