Page - 206 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Image of the Page - 206 -
Text of the Page - 206 -
206 6 SolvingNonlinearAlgebraicEquations
F_value = F(x)
F_norm = np.linalg.norm(F_value, ord=2) # l2 norm of vector
iteration_counter = 0
while abs(F_norm) > eps and iteration_counter < 100:
delta = np.linalg.solve(J(x), -F_value)
x = x + delta
F_value = F(x)
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter += 1
# Here, either a solution is found, or too many iterations
if abs(F_norm) > eps:
iteration_counter = -1
return x, iteration_counter
Wecan test the functionNewton_systemwith the2 2 system(6.11)-(6.12):
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’ % error_norm
print ’norm of error =%g’ % error_norm
Here, the testing is based on theL2normof the error vector. Alternatively,we
could test against the values of x that the algorithmfinds, with appropriate toler-
ances. For example, as chosen for the error norm, if eps=0.0001, a tolerance of
10 4 canbeused forx[0]andx[1].
6.7 Exercises
Exercise6.1:UnderstandwhyNewton’smethodcanfail
The purpose of this exercise is to understandwhenNewton’smethodworks and
fails. To this end, solve tanhxD0byNewton’smethodandstudy the intermediate
details of the algorithm. Startwithx0 D 1:08. Plot the tangent in each iterationof
Newton’smethod. Then repeat the calculations and the plottingwhenx0 D 1:09.
Explainwhatyouobserve.
Filename:Newton_failure.*.
back to the
book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python"
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Title
- Programming for Computations – Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2016
- Language
- English
- License
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 248
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik