Seite - 198 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 198 -
Text der Seite - 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, Band Second Edition
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Band
- Second Edition
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2020
- Sprache
- englisch
- Lizenz
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 356
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik