Homepage › Solution manuals › Gilbert Strang › Linear Algebra and Learning from Data › Exercise 6.1.13
Exercise 6.1.13
Answers
We can also apply Newton’s method to . Depends on the initial value, we get different solutions each time.
from scipy import optimize import numpy as np import math import matplotlib.pyplot as plt def f(x): return x**2+1 def df(x): return 2*x #root = optimize.newton(f, 1.5, fprime = lambda x: math.cos(x)) #root def newton(f, df, x0, maxit=500): x = x0 xs, ys = [x0], [f(x0)] for it in np.arange(maxit): x = x - f(x)/df(x) if np.abs(f(x)) <= 1.0e-12: print(’Find␣the␣root:’, x, f(x), ’␣at␣iteration:␣’, it) break xs.append(x) ys.append(f(x)) print("Exhausted␣all␣", maxit, "␣iterations.") return x, f(x), xs, ys print("####␣Problem␣VI.1.12") v, fv, xs, ys = newton(f, df, 2) print("####␣Problem␣VI.1.13") v13, fv13, xs13, ys13 = newton(math.sin, math.cos, 7)
\#\#\#\# Problem VI.1.12 Exhausted all 500 iterations. \#\#\#\# Problem VI.1.13 Find the root: 6.283185307179586 -2.4492935982947064e-16 at iteration: 3 Exhausted all 500 iterations.
plt.plot(xs, ys, ’.’)
[<matplotlib.lines.Line2D at 0x292ac0c5128>]
2020-03-20 00:00