Demonstration of two methods:
brentrq()
, for a root known to lie an interval [a,b]
, where a
and b
have opposite signsnewton()
, for a root known to be near some point a
Let's find the points where $ \tan x = x$.
Marty Ligare, September 2019
import numpy as np
from scipy import optimize
import matplotlib as mpl
import matplotlib.pyplot as plt
# 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
def f(x):
return np.tan(x) - x
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)$');
# Using interactive plot features helps here
root1 = optimize.newton(f, 4.5)
root2 = optimize.brentq(f,2,4.6)
root1, root2
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
%load_ext version_information
version_information numpy, scipy, matplotlib