Seite - 194 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python
Bild der Seite - 194 -
Text der Seite - 194 -
194 6 SolvingNonlinearAlgebraicEquations
-1.05895313436
0.989404207298
-0.784566773086
0.36399816111
-0.0330146961372
2.3995252668e-05
Adjustingx0 slightly to 1.09 gives division by zero! The approximations com-
putedbyNewton’smethodbecome
-1.09331618202
1.10490354324
-1.14615550788
1.30303261823
-2.06492300238
13.4731428006
-1.26055913647e+11
Thedivisionbyzeroiscausedbyx7 D 1:26055913647 1011,becausetanh.x7/
is 1.0 tomachine precision, and thenf 0.x/ D 1 tanh.x/2 becomes zero in the
denominator inNewton’smethod.
The underlying problem, leading to the division by zero in the above example,
is that Newton’s method diverges: the approximations move further and further
away from x D 0. If it had not been for the division by zero, the condition in
thewhile loopwould always be true and the loopwould run forever. Divergence
ofNewton’smethodoccasionally happens, and the remedy is to abort themethod
whenamaximumnumberof iterations is reached.
Another disadvantage of the naive_Newton function is that it calls the f.x/
function twice asmany times asnecessary. This extrawork is of noconcernwhen
f.x/ isfast toevaluate,butin large-scaleindustrialsoftware,onecall tof.x/might
takehoursordays, and then removingunnecessarycalls is important. Thesolution
inour function is to store thecallf(x) inavariable (f_value)and reuse thevalue
insteadofmakinganewcallf(x).
To summarize,wewant towrite an improved function for implementingNew-
ton’smethodwherewe
avoiddivisionbyzero
allowamaximumnumberof iterations
avoid theextraevaluationoff.x/
Amore robustandefficientversionof the function, inserted inacompleteprogram
Newtons_method.pyfor solvingx2 9D0, is listedbelow.
def Newton(f, dfdx, x, eps):
f_value = f(x)
iteration_counter = 0
while abs(f_value) > eps and iteration_counter < 100:
try:
x = x - float(f_value)/dfdx(x)
Programming for Computations – Python
A Gentle Introduction to Numerical Simulations with Python
- Titel
- Programming for Computations – Python
- Untertitel
- A Gentle Introduction to Numerical Simulations with Python
- Autoren
- Svein Linge
- Hans Petter Langtangen
- Verlag
- Springer Open
- Datum
- 2016
- Sprache
- englisch
- Lizenz
- CC BY-NC 4.0
- ISBN
- 978-3-319-32428-9
- Abmessungen
- 17.8 x 25.4 cm
- Seiten
- 248
- Schlagwörter
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Kategorie
- Informatik