Page - 198 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 198 -
Text of the Page - 198 -
198 7 SolvingNonlinearAlgebraicEquations
# Here, either a solution is found, or too many iterations
if abs(F_norm) > eps:
iteration_counter = -1
return x, iteration_counter
Wecantest thefunctionNewton_systemwiththe2×2system(7.10)and(7.11):
def test_Newton_system1():
from numpy import cos, sin, pi, exp
def F(x):
return np.array(
[x[0]**2 - x[1] + x[0]*cos(pi*x[0]),
x[0]*x[1] + exp(-x[1]) - x[0]**(-1.)])
def J(x):
return np.array(
[[2*x[0] + cos(pi*x[0]) - pi*x[0]*sin(pi*x[0]), -1],
[x[1] + x[0]**(-2.), x[0] - exp(-x[1])]])
expected = np.array([1, 0])
tol = 1e-4
x, n = Newton_system(F, J, x=np.array([2, -1]), eps=0.0001)
print(n, x)
error_norm = np.linalg.norm(expected - x, ord=2)
assert error_norm < tol, ’norm of error ={:g}’.format(error_norm)
print(’norm of error ={:g}’.format(error_norm))
Here, the testing is based on the L2 norm6 of the error vector. Alternatively,
we could test against the values of x that the algorithm finds, with appropriate
tolerances. For example, as chosen for the error norm, ifeps=0.0001, a tolerance
of10−4 canbeused forx[0]andx[1].
7.7 Exercises
Exercise7.1:UnderstandWhyNewton’sMethod CanFail
The purpose of this exercise is to understand when Newton’s method works and
fails. To this end, solve tanhx=0 byNewton’smethodandstudy the intermediate
details of the algorithm. Start withx0 = 1.08. Plot the tangent in each iteration of
Newton’s method. Then repeat the calculations and the plotting when x0 = 1.09.
Explainwhatyouobserve.
Filename:Newton_failure.*.
Exercise7.2:SeeIf theSecantMethod Fails
Does the secant method behave better than Newton’s method in the problem
describedin Exercise7.1?Try the initial guesses
1. x0 =1.08andx1 =1.09
2. x0 =1.09andx1 =1.1
6 https://en.wikipedia.org/wiki/Norm_(mathematics)#Euclidean_norm.
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik