186
7 Solving Nonlinear Algebraic Equations
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 construction. 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 informative error message and stop the program in a gentler way.
Calling sys.exit with 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 operating system can then be used by other programs to detect
that our program failed.
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’s method. With iteration_counter we can easily extend the condition in
the while loop such that no more iterations take place when the number of iterations
reaches 100. We could easily let this limit be an argument to the function rather than
a fixed constant.
The Newton function returns the approximate solution and the number of
iterations. The latter equals −1 if the convergence criterion |f (x)| < < was not
reached within the maximum number of iterations. In the calling code, we print out
3 Professional programmers would avoid calling sys.exit inside a function. Instead, they would
raise a new exception with an informative error message, and let the calling code have another
try-except construction to stop the program.
Précédent

- 207/350

Suivant