Page - 191 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 191 -
Text of the Page - 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, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik