#!/usr/bin/env python # coding: utf-8 # # Newton method # Consider the function # $$ # f(x) = \exp(x) - \frac{3}{2} - \arctan(x) # $$ # In[1]: get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'") from numpy import linspace,abs from sympy import Symbol,exp,atan,diff,lambdify from matplotlib.pyplot import figure,subplot,plot,grid,title # We define the function using sympy and automatically compute its derivative. Then we make functions out of these. # In[2]: x = Symbol('x') # Define the function f = exp(x)-3.0/2.0-atan(x) # Compute its derivative df = diff(f,x) print("f = ", f) print("df= ", df) # Make functions F = lambdify(x, f, modules=['numpy']) DF = lambdify(x, df, modules=['numpy']) # Plot the functions X = linspace(-1,1,100) figure(figsize=(9,4)) subplot(1,2,1) plot(X,F(X)) grid(True) title('Function') subplot(1,2,2) plot(X,DF(X)) grid(True) title('Derivative'); # Now we implement the Newton method. We have to specify the maximum number of iterations, an initial guess and a tolerance to decide when to stop. # In[3]: M = 20 # maximum iterations x = 0.5 # initial guess eps = 1e-14 # relative tolerance on root f = F(x) for i in range(M): df = DF(x) dx = -f/df x = x + dx e = abs(dx) f = F(x) print("%6d %22.14e %22.14e %22.14e" % (i,x,e,abs(f))) if e < eps * abs(x): break # ## Exercise # # Modify the above Newton method implemention to use `while` loop.