This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

# Root Finding Problem Statement¶

The root or zero of a function, $$f(x)$$, is an $$x_r$$ such that $$f(x_r) = 0$$. For functions such as $$f(x) = x^2 - 9$$, the roots are clearly 3 and $$-3$$. However, for other functions such as $$f(x) = {\rm cos}(x) - x$$, determining an analytic, or exact, solution for the roots of functions can be difficult. For these cases, it is useful to generate numerical approximations of the roots of $$f$$ and understand the limitations in doing so.

TRY IT! Using fsolve function from scipy to compute the root of $$f(x) = {\rm cos}(x) - x$$ near $$-2$$. Verify that the solution is a root (or close enough).

import numpy as np
from scipy import optimize

f = lambda x: np.cos(x) - x
r = optimize.fsolve(f, -2)
print("r =", r)

# Verify the solution is a root
result = f(r)
print("result=", result)
r = [0.73908513]
result= [0.]

TRY IT! The function $$f(x) = \frac{1}{x}$$ has no root. Use the fsolve function to try to compute the root of $$f(x) = \frac{1}{x}$$. Turn on the full_output to see what’s going on. Remember to check the documentation for details.

f = lambda x: 1/x

r, infodict, ier, mesg = optimize.fsolve(f, -2, full_output=True)
print("r =", r)

result = f(r)
print("result=", result)

print(mesg)
r = [-3.52047359e+83]
result= [-2.84052692e-84]
The number of calls to function has reached maxfev = 400.

We can see that, the value r we got is not a root, even though the f(r) is a very small number. Since we turned on the full_output, which have more information. A message will be returned if no solution is found, and we can see mesg details for the cause of failure - “The number of calls to function has reached maxfev = 400.”