Finding roots

Demonstration of two methods:

  • brentrq(), for a root known to lie an interval [a,b], where a and b have opposite signs
  • newton(), for a root known to be near some point a

Let's find the points where $ \tan x = x$.

Marty Ligare, September 2019

In [3]:
import numpy as np
from scipy import optimize

import matplotlib as mpl       
import matplotlib.pyplot as plt
In [4]:
# Following is an Ipython magic command that puts figures in the  notebook.
%matplotlib notebook

# M.L. modification of matplotlib defaults
# Changes can also be put in matplotlibrc file, 
# or effected using mpl.rcParams[]
mpl.style.use('classic')
plt.rc('figure', figsize = (6, 4.5))            # Reduces overall size of figures
plt.rc('axes', labelsize=16, titlesize=14)
plt.rc('figure', autolayout = True)             # Adjusts supblot parameters for new size
In [5]:
def f(x):
    return np.tan(x) - x
In [6]:
plt.figure()
x = np.linspace(0,10,201)
y = np.tan(x) 
plt.ylim(-10,10)
plt.axhline(0, color='k')
plt.axvline(0,color='k')
plt.plot(x,y)
plt.plot(x,x)
plt.xlabel('$x$')
plt.ylabel('$f(x)$');
In [7]:
# Using interactive plot features helps here
root1 = optimize.newton(f, 4.5) 
root2 = optimize.brentq(f,2,4.6)
In [8]:
root1, root2
Out[8]:
(4.493409457909337, 4.4934094579089185)

Version Information

version_information is from J.R. Johansson (jrjohansson at gmail.com); see Introduction to scientific computing with Python for more information and instructions for package installation.

version_information is installed on the linux network at Bucknell

In [9]:
%load_ext version_information
In [10]:
version_information numpy, scipy, matplotlib
Out[10]:
SoftwareVersion
Python3.7.7 64bit [GCC 7.3.0]
IPython7.16.1
OSLinux 3.10.0 1062.9.1.el7.x86_64 x86_64 with centos 7.7.1908 Core
numpy1.18.5
scipy1.5.2
matplotlib3.3.0
Fri Aug 07 11:55:55 2020 EDT
In [ ]: