#!/usr/bin/env python # coding: utf-8 # # Newton method with double root # Consider the function # $$ # f(x) = (x-1)^2 \sin(x) # $$ # for which $x=1$ is a double root. # In[1]: get_ipython().run_line_magic('matplotlib', 'inline') get_ipython().run_line_magic('config', "InlineBackend.figure_format = 'svg'") from numpy import sin,cos,linspace,zeros,abs from matplotlib.pyplot import plot,xlabel,ylabel,grid # In[2]: def f(x): return (x-1.0)**2 * sin(x) def df(x): return 2.0*(x-1.0)*sin(x) + (x-1.0)**2 * cos(x) # In[3]: x = linspace(0.0,2.0,100) plot(x,f(x)) xlabel('x') ylabel('f(x)') grid(True) # In[4]: def newton(x0,m): n = 50 x = zeros(50) x[0] = x0 print("%6d %24.14e" % (0,x[0])) for i in range(1,50): x[i] = x[i-1] - m*f(x[i-1])/df(x[i-1]) if i > 1: r = (x[i] - x[i-1])/(x[i-1]-x[i-2]) else: r = 0.0 print("%6d %24.14e %14.6e" % (i,x[i],r)) if abs(f(x[i])) < 1.0e-14: break # We first apply the standard newton method. # In[5]: newton(2.0,1) # Newton method is converging linearly. Now try the modified Newton method. # In[6]: newton(2.0,2)