"""File: bisect1.py Purpose: Find a root of a function given initial guesses that bracket a root -- i.e., one is larger, the other is smaller Run: python bisect1.py Input: maximum error tolerance (float) maximum number of iterations (int) value less than root (float) value greater than root (float) """ #---------------------------------------------------------------------- def f(x): """Function whose roots are +/- sqrt(2) """ return x*x - 2 #---------------------------------------------------------------------- def bisect(lo, hi, tol, max_iter): est = (hi + lo)/2.0 iter = 1; err_bd = (hi-lo)/2.0 while err_bd > tol and iter < max_iter: if f(est) == 0: break elif f(est)*f(hi) > 0: hi = est else: lo = est est = (hi + lo)/2.0 iter = iter + 1; err_bd = (hi-lo)/2.0 # print "iter =", iter, ", est =", est print "The number of iterations was", iter print "The error in the estimate", est, "is less than or equal to", err_bd if err_bd > tol: return None else: return est #---------------------------------------------------------------------- # Program starts here tol = float(raw_input("Enter the maximum tolerance\n ")) max_iter = int(raw_input("Enter the maximum number of iterations\n ")) lo = float(raw_input("Enter a value < the zero of f\n ")) hi = float(raw_input("Enter a value > the zero of f\n ")) while f(lo)*f(hi) > 0: print "Enter values for which the product f(lo)*f(hi) < 0" lo = float(raw_input("Enter a value < the zero of f\n ")) hi = float(raw_input("Enter a value > the zero of f\n ")) est = bisect(lo, hi, tol, max_iter) if est == None: print "The iteration failed to converge" else: print "The iteration converged" print "The estimate is", est print "f(", est, ") = ", f(est)