# L-15 MCS 275 Mon 15 Feb 2010 : bisection.py # If f(a)*f(b) < 0 for some continuous function, # then there is a root r: f(r) = 0, a <= r <= b. def bisect(f,a,b): """ If (a,b) contains a root of f, the on return is a smaller (a,b) containing a root of f. The string f is a function in x. """ m = (a + b)/2 x = a; fa = eval(f) x = m; fm = eval(f) if fm*fa < 0: return (a,m) else: return (m,b) def main(): """ Applies the bisection method to find a root of some function. """ f = raw_input('Give function in x : ') while True: a = float(input('give left bound a : ')) b = float(input('give right bound b : ')) x = a; fa = eval(f) x = b; fb = eval(f) if fa*fb >= 0: print 'f(a) = ', fa, ', f(b) = ', fb print 'please try again' else: break print 'a =', a, ', b = ', b while True: (a,b) = bisect(f,a,b) print 'a =', a, ', b = ', b ans = raw_input('continue ? ') if ans != 'y': break main()