## Jupyter Snippet CB2nd 01_root

Jupyter Snippet CB2nd 01_root

# 9.1. Finding the root of a mathematical function

``````import numpy as np
import scipy as sp
import scipy.optimize as opt
import matplotlib.pyplot as plt
%matplotlib inline
``````
``````def f(x):
return np.cos(x) - x
``````
``````x = np.linspace(-5, 5, 1000)
y = f(x)
fig, ax = plt.subplots(1, 1, figsize=(5, 3))
ax.axhline(0, color='k')
ax.plot(x, y)
ax.set_xlim(-5, 5)
``````

``````opt.bisect(f, -5, 5)
``````
``````0.739
``````
``````fig, ax = plt.subplots(1, 1, figsize=(5, 3))
ax.axhline(0, color='k')
ax.plot(x, y)
# The zorder argument is used to put
# the dot on top of the other elements.
ax.scatter([_], [0], c='r', s=100,
zorder=10)
ax.set_xlim(-5, 5)
``````

``````opt.brentq(f, -5, 5)
``````
``````0.739
``````
``````%timeit opt.bisect(f, -5, 5)
%timeit opt.brentq(f, -5, 5)
``````
``````34.5 µs ± 855 ns per loop (mean ± std. dev. of 7 runs,
10000 loops each)
7.71 µs ± 170 ns per loop (mean ± std. dev. of 7 runs,
100000 loops each)
``````