Web-Books
in the Austria-Forum
Austria-Forum
Web-Books
Informatik
Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Page - 191 -
  • User
  • Version
    • full version
    • text only version
  • Language
    • Deutsch - German
    • English

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 -

Image of the Page - 191 - in Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition

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.
back to the  book Programming for Computations – Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition"
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
Web-Books
Library
Privacy
Imprint
Austria-Forum
Austria-Forum
Web-Books
Programming for Computations – Python