Simple example of numerical integration of a one-dimensional and multi-dimensional integrals using the quad()
from the integrate
sub-module of scipy
.
Marty Ligare, August 2020
import numpy as np
from scipy import integrate # importing sub-module of scipy
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. modifications of matplotlib defaults using syntax of v.2.0
# More info at http://matplotlib.org/2.0.0/users/deflt_style_changes.html
# 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 func1(x): # Continuous function
return x**3
def func2(x): # Discontinuous function
if x< 2:
return x**2
if x>2:
return x**2
def func3(x): # Function with a singluarity
return np.sin(x-2)/(x-2)
value, error = integrate.quad(func1,1,2)
value, error
If there are discontinuities or singularities, quad will fail, eg.,
value, error = integrate.quad(func2,1,3)
value, error
Specify troublesome points:
value, error = integrate.quad(func2,1,3,points=[2,])
value, error
value, error = integrate.quad(func3,0,4,points=[2,])
value, error
With $g$, $h$, $q$, and $r$ defined normally:
def func4(z,y,x): # ORDER OF ARGUMENTS IMPORTANT
return 1
def g(x):
return 0
def h(x):
return np.sqrt(xulim**2-x**2)
def q(x,y):
return 0
def r(x,y):
return np.sqrt(xulim**2-x**2-y**2)
xllim = 0
xulim = 2
value, error = integrate.tplquad(func4, xllim, xulim, g, h, q, r)
8*value, error, 4*np.pi*xulim**3/3.
With $g$, $h$, $q$, and $r$ defined more concisely:
g = lambda x: 0
h = lambda x: np.sqrt(xulim**2-x**2)
q = lambda x,y: 0
r = lambda x,y: np.sqrt(xulim**2-x**2-y**2)
xllim = 0
xulim = 2
value, error = integrate.tplquad(func4, xllim, xulim, g, h, q, r)
8*value, error, 4*np.pi*xulim**3/3.
Or even more concisely:
xllim = 0
xulim = 2
value, error = integrate.tplquad(func4, xllim, xulim, \
lambda x:0, lambda x:np.sqrt(xulim**2-x**2), \
lambda x,y:0, lambda x,y:np.sqrt(xulim**2-x**2-y**2))
8*value, error, 4*np.pi*xulim**3/3.
def func5(phi,theta,r):
return r**2*np.sin(theta)
rllim = 0
rulim = 2
value, error = integrate.tplquad(func5, rllim, rulim, \
lambda theta:0, lambda theta:np.pi, \
lambda theta,phi:0, lambda theta,phi:2.*np.pi)
value, error, 4*np.pi*xulim**3/3.
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