Seite - 186 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 186 -
Text der Seite - 186 -
186 7 SolvingNonlinearAlgebraicEquations
iteration_counter = 0
while abs(f_value) > eps and iteration_counter < 100:
try:
x = x - f_value/dfdx(x)
except ZeroDivisionError:
print(’Error! - derivative zero for x = ’, x)
sys.exit(1) # Abort with error
f_value = f(x)
iteration_counter = iteration_counter + 1
# Here, either a solution is found, or too many iterations
if abs(f_value) > eps:
iteration_counter = -1
return x, iteration_counter
if __name__ == ’__main__’:
def f(x):
return x**2 - 9
def dfdx(x):
return 2*x
solution, no_iterations = Newton(f, dfdx, x=1000, eps=1.0e-6)
if no_iterations > 0: # Solution found
print(’Number of function calls: {:d}’.format(1+2*no_iterations))
print(’A solution is: {:f}’.format(solution))
else:
print(’Solution not found!’)
Handling of the potential division by zero is done by a try-except construc-
tion.3
The division by zero will always be detected and the program will be stopped.
The main purpose of our way of treating the division by zero is to give the user a
more informativeerrormessageandstop theprogramina gentlerway.
Calling sys.exitwith an argument different from zero (here 1) signifies that
the program stopped because of an error. It is a good habit to supply the value 1,
because tools in the operatingsystem can then be used by other programsto detect
thatourprogramfailed.
To prevent an infinite loop because of divergent iterations, we have introduced
the integer variable iteration_counter to count the number of iterations in
Newton’smethod.Withiteration_counterwecaneasilyextendtheconditionin
thewhile loopsuchthatnomoreiterationstakeplacewhenthenumberofiterations
reaches100.Wecouldeasily let this limitbeanargumentto thefunctionrather than
afixedconstant.
The Newton function returns the approximate solution and the number of
iterations. The latter equals −1 if the convergence criterion |f(x)| < was not
reachedwithin themaximumnumberof iterations. In thecallingcode,we printout
3 Professional programmers would avoid callingsys.exit inside a function. Instead, they would
raise a new exception with an informative error message, and let the calling code have another
try-exceptconstruction to stop the program.
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