Page - 178 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 178 -
Text of the Page - 178 -
178 7 SolvingNonlinearAlgebraicEquations
Implementation Given some Python implementation f(x) of our mathematical
function, a straightforward implementation of the above algorithm that quits after
findingoneroot, looks like
x = linspace(0, 4, 10001)
y = f(x)
root = None # Initialization
for i in range(len(x)-1):
if y[i]*y[i+1] < 0:
root = x[i] - (x[i+1] - x[i])/(y[i+1] - y[i])*y[i]
break # Jump out of loop
elif y[i] == 0:
root = x[i]
break # Jump out of loop
if root is None:
print(βCould not find any root in [{:g}, {:g}]β.format(x[0], x[-1]))
else:
print(βFind (the first) root as x={:.17f}β.format(root))
(See thefilebrute_force_root_finder_flat.py.)
Notetheniceuseofsettingroot toNone:wecansimplytestif root is None
to see if we found a root and overwrote theNone value, or if we did not find any
rootamongthe testedpoints.
Running this programwith somefunction, sayf(x)= eβx2 cos(4x) (whichhas
a solution at x = Ο8), gives the root 0.39269910538048097,which has an error of
2.4Γ10β8. Increasingthenumberofpointswitha factorof tengivesa rootwithan
errorof2.9Γ10β10.
After such a quick βflatβ implementation of an algorithm, we should always try
tooffer thealgorithmasaPythonfunction,applicable toaswideaproblemdomain
aspossible.Thefunctionshould takef andanassociated interval [a,b]as input,as
well asa numberofpoints (n), andreturna list of all the roots in [a,b].Here isour
candidatefora goodimplementationof thebrute force rootfindingalgorithm:
def brute_force_root_finder(f, a, b, n):
from numpy import linspace
x = linspace(a, b, n)
y = f(x)
roots = []
for i in range(n-1):
if y[i]*y[i+1] < 0:
root = x[i] - (x[i+1] - x[i])/(y[i+1] - y[i])*y[i]
roots.append(root)
elif y[i] == 0:
root = x[i]
roots.append(root)
return roots
(See thefilebrute_force_root_finder_function.py.)
This timeweuseanothereleganttechniqueto indicate if rootswerefoundornot:
roots is anempty list if the rootfindingwasunsuccessful,otherwise it containsall
the roots.Applicationof the function to thepreviousexamplecanbecodedas
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