Lauri Ruotsalainen, 2010 (based on the application "Root Finding Using Bisection" by William Stein)
Also includes listing steps in a HTML table.
Pictures:
# Newton's Method (based on the application "Root Finding Using Bisection" by William Stein)
# Also includes listing steps in a HTML table
# Lauri Ruotsalainen, 2010
def newton_method(f, c, maxn, h):
f(x) = f
midpoints = [c]
round = 1
while True:
c = c-f(c)/derivative(f(x))(x=c)
midpoints.append(c)
if f(c-h)*f(c+h) < 0 or round == maxn:
break
round += 1
return c, midpoints
@interact
def newton_method_interact(
f = x^2 - 2,
c = 6,
hh = slider(-16, -1, 1, -3, label="Precision 2h"),
maxn = slider(0, 15, 1, 10, label="Max rounds"),
interval = input_box(default = (0,6), label="Interval"),
list_steps = checkbox(default=False, label="List steps"),
):
f(x) = f
h = 10^hh
c, midpoints = newton_method(f, float(c), maxn, h/2.0)
html("$\\text{Precision 2h = }%s$"%float(h))
html("$\\text{c = }%s$"%c)
html("$\\text{f(c) = }%s"%f(c))
html("$\\text{Iterations = }%s"%len(midpoints))
if list_steps:
s = "<br><br><table border=1 cellpadding=5>"
s += "<tr><td>$n$</td><td>$x_n$</td><td>$f(x_n)$</td><td>$f(x_n-h)f(x_n+h)$</td></tr>"
for i, c in enumerate(midpoints):
s += "<tr><td>$%s$</td><td>$%s$</td><td>$%s$</td><td>$%s$</td></tr>"%(i, c, f(c), f(c-h)*f(c+h))
s += "</table>"
html(s)
else:
P = plot(f, x, interval, color="blue")
L = sum(line([(c, 0), (c, f(c))], color="green") for c in midpoints[:-1])
for i in range(len(midpoints) - 1):
L += line([(midpoints[i], f(midpoints[i])), (midpoints[i+1], 0)], color="red")
show(P + L, xmin=interval[0], xmax=interval[1], ymin=P.ymin(), ymax=P.ymax())