Seite - 191 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Band Second Edition
Bild der Seite - 191 -
Text der Seite - 191 -
7.4 TheBisectionMethod 191
The sketched strategy seems reasonable, so let us write a reusable function that
cansolvea generalalgebraicequationf(x)=0(bisection_method.py):
import sys
def bisection(f, x_L, x_R, eps):
f_L = f(x_L)
if f_L*f(x_R) > 0:
print(’Error! Function does not have opposite \
signs at interval endpoints!’)
sys.exit(1)
x_M = (x_L + x_R)/2.0
f_M = f(x_M)
iteration_counter = 1
while abs(f_M) > eps:
if f_L*f_M > 0: # i.e. same sign
x_L = x_M
f_L = f_M
else:
x_R = x_M
x_M = (x_L + x_R)/2
f_M = f(x_M)
iteration_counter = iteration_counter + 1
return x_M, iteration_counter
if __name__ == ’__main__’:
def f(x):
return x**2 - 9
a = 0; b = 1000
solution, no_iterations = bisection(f, a, b, eps=1.0e-6)
print(’Number of function calls: {:d}’.format(1 + 2*no_iterations))
print(’A solution is: {:f}’.format(solution))
Note thatwefirst checkiff changessign in [a,b],because that isa requirement
for the algorithmtowork.Thealgorithmalso reliesonacontinuousf(x) function,
but this is verychallengingfora computercode tocheck.
Weget thefollowingprintoutto thescreenwhenbisection_method.pyis run:
Number of function calls: 63
A solution is: 3.000000
We notice that the number of function calls is much higher than with the previous
methods.
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