In [27]:
%matplotlib inline

import matplotlib
import numpy as np
import matplotlib.pyplot as pt
In [28]:
def f(x):
    return np.arctan(x)

def df(x):
    return 1/(1 + x**2)

xmesh = np.linspace(-20,20,100)
pt.plot(xmesh,f(xmesh))

#xk = [2]  #this is a bad initial guess
xk = [1]  #this is a good initial guess
In [29]:
#Do this next cell many times
x = xk[-1] #grab last guess
slope = df(x)

#plot approximate function
pt.plot(xmesh,f(xmesh))
pt.plot(xmesh, f(x) + slope*(xmesh - x))
pt.plot(x,f(x),'o')
pt.ylim([-2,2])
pt.axhline(0,color="black")

#compute approximate root/next iterate
xnew = x - f(x)/slope
xk.append(xnew)
print(xnew)
-0.570796326795
In [ ]: