"""File: newton1.py Purpose: Implement Newton's method to approximately solve f(x) = 0 Run: python newton1.py Input: tol: approximate solution must be within tol of the actual solution guess: the initial guess at a solution Output: Whether the method converged If it converges, the approx solution and the value of the function at the approx solution. Note: This program may have an infinite loop """ #---------------------------------------------------------------------- def f(x): """Solutions to f(x) = 0 are +/- sqrt(2)""" return x*x - 2 def f_prime(x): """Derivative of f(x)""" return 2*x #---------------------------------------------------------------------- def newton(g, tol): if (f_prime(g) == 0): print "f'(", g ,") = 0" return None new_g = g - f(g)/f_prime(g) err_bd = abs(new_g - g) while err_bd > tol: g = new_g if (f_prime(g) == 0): print "f'(", g ,") = 0" return None new_g = g - f(g)/f_prime(g) err_bd = abs(new_g - g) if err_bd <= tol: return new_g else: return None #---------------------------------------------------------------------- # main tol = float(raw_input("What's the maximum acceptable error?\n ")) guess = float(raw_input("What's the initial guess?\n ")) est = newton(guess, tol) if est == None: print "The method failed" else: print "The method converged" print "The approximate solution to f(x) = 0 is", est print "f(", est, ") =", f(est)