<jupyter_start><jupyter_text>> This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python.  9.1. Finding the root of a mathematical function 1. Let's import NumPy, SciPy, scipy.optimize, and matplotlib.<jupyter_code>import numpy as np
import scipy as sp
import scipy.optimize as opt
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>2. We define the mathematical function $f(x)=\cos(x)-x$ in Python. We will try to find a root of this function numerically, which corresponds to a fixed point of the cosine function.<jupyter_code>f = lambda x: np.cos(x) - x<jupyter_output><empty_output><jupyter_text>3. Let's plot this function on the interval $[-5, 5]$.<jupyter_code>x = np.linspace(-5, 5, 1000)
y = f(x)
plt.figure(figsize=(5,3));
plt.plot(x, y);
plt.axhline(0, color='k');
plt.xlim(-5,5);<jupyter_output><empty_output><jupyter_text>4. We see that this function has a unique root on this interval (this is because the function's sign changes on this interval). The scipy.optimize module contains a few root-finding functions that are adapted here. For example, the `bisect` function implements the **bisection method** (also called the **dichotomy method**). It takes as input the function and the interval to find the root in.<jupyter_code>opt.bisect(f, -5, 5)<jupyter_output><empty_output><jupyter_text>Let's visualize the root on the plot.<jupyter_code>plt.figure(figsize=(5,3));
plt.plot(x, y);
plt.axhline(0, color='k');
plt.scatter([_], [0], c='r', s=100);
plt.xlim(-5,5);<jupyter_output><empty_output><jupyter_text>5. A faster and more powerful method is `brentq` (Brent's method). This algorithm also requires that $f$ is continuous and that $f(a)$ and $f(b)$ have different signs.<jupyter_code>opt.brentq(f, -5, 5)<jupyter_output><empty_output><jupyter_text>The `brentq` method is faster than `bisect`. If the conditions are satisfied, it is a good idea to try Brent's method first.<jupyter_code>%timeit opt.bisect(f, -5, 5)
%timeit opt.brentq(f, -5, 5)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12459471977767485, 'fraction_numerical': 0.018527095877721167, 'mean_word_length': 5.990291262135922, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 30, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '565096', 'license': 'BSD-2-Clause', 'n_tokens_mistral': 780, 'n_tokens_neox': 738, 'n_words': 245, 'path': 'notebooks/chapter09_numoptim/01_root.ipynb', 'repo_name': 'khanparwaz/PythonProjects', 'size': '2159'}