7.3 The Secant Method
189
Fig. 7.2 Illustrates the use of secants in the secant method when solving x 2 −9 = 0, x ∈ [0, 1000].
From two chosen starting values, x 0 = 1000 and x 1 = 700 the crossing x 2 of the corresponding
secant with the x axis is computed, followed by a similar computation of x 3 from x 1 and x 2
iteration_counter = 0
while abs(f_x1) > eps and iteration_counter < 100:
try:
denominator = (f_x1 - f_x0)/(x1 - x0)
x = x1 - f_x1/denominator
except ZeroDivisionError:
print(’Error! - denominator zero for x = ’, x)
sys.exit(1)
# Abort with error
x0 = x1
x1 = x
f_x0 = f_x1
f_x1 = f(x1)
iteration_counter = iteration_counter + 1
# Here, either a solution is found, or too many iterations
if abs(f_x1) > eps:
iteration_counter = -1
return x, iteration_counter
if __name__ == ’__main__’:
def f(x):
return x**2 - 9
x0 = 1000;
x1 = x0 - 1
solution, no_iterations = secant(f, x0, x1, eps=1.0e-6)
if no_iterations > 0:
# Solution found
Précédent

- 210/350

Suivant