"""File: newton.py Purpose: Implement Newton's method to approximately solve f(x) = 0 Run: python newton.py Input: tol: approximate solution must be within tol of the actual solution max_iter: program should make no more than this many passes through the while loop in the newton function guess: the initial guess at a solution Output: Number of iterations Whether the method converged If it converges, the approx solution and the value of the function at the approx solution. """ #---------------------------------------------------------------------- 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, max_iter): if (f_prime(g) == 0): print "f'(", g ,") = 0 after 0 iterations" return None new_g = g - f(g)/f_prime(g) err_bd = abs(new_g - g) iters = 1 while err_bd > tol and iters < max_iter: g = new_g if (f_prime(g) == 0): print "f'(", g ,") = 0 after", iters, "iterations" return None new_g = g - f(g)/f_prime(g) err_bd = abs(new_g - g) iters = iters + 1 print "The method completed", iters, "iterations" if err_bd <= tol: return new_g else: return None #---------------------------------------------------------------------- # main tol = float(raw_input("What's the maximum acceptable error?\n ")) max_iter = int(raw_input("What's the maximum number of passes?\n ")) guess = float(raw_input("What's the initial guess?\n ")) est = newton(guess, tol, max_iter) 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)