Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 Sergio Rojas (srojas@usb.ve) and Erik A Christensen (erikcny@aol.com).
This chapter is without a doubt one of the most interesting chapters in this book. It covers with great detail the definition and manipulation of functions (one or several variables), the extraction of their roots, extreme values (optimization), computation of derivatives, integration, interpolation, regression, and applications to the solution of ordinary differential equations.
In [1]:
import scipy.special
import numpy
In [2]:
a=scipy.special.exp10(-16)
numpy.log(1+a)
Out[2]:
In [3]:
scipy.special.log1p(a)
Out[3]:
In [12]:
P1=numpy.poly1d([1,0,3]) # using coefficients
print(P1)
In [5]:
print(P1.r) #roots
In [6]:
print(P1.o)#order
In [7]:
print (P1.deriv()) # derivative
In [10]:
P2=numpy.poly1d([1,1,1], True) # using roots
print(P2)
In [6]:
P2=numpy.poly1d([1,1,1], True, variable='z')
print (P2)
In [13]:
P1( scipy.arange(10) ) # evaluate at 0,1,...,9
Out[13]:
In [14]:
P1.__call__(scipy.arange(10)) # same evaluation
Out[14]:
Let's consider and evaluate the approximation of the natural logarithm:
In [9]:
Px=numpy.poly1d([-(1./2.),1,0])
In [10]:
print(Px)
In [15]:
a=1./10000000000000000.
print(a)
In [12]:
Px(a)
Out[12]:
In [21]:
P1=numpy.poly1d([1,0,1])
print(P1)
As mentioned in the book, the following four (In []) lines of code show that the respective commands are equivalent, as shown by the corresponding Out[] lines
In [17]:
print(scipy.polyadd(P1, scipy.poly1d([2,1])))
In [18]:
print(scipy.polyadd(P1, [2,1]))
In [19]:
print(P1 + scipy.poly1d([2,1]))
In [20]:
print(P1 + [2,1])
In [16]:
P1/[2,1]
Out[16]:
As mentioned in the book, the output sould be read as follows:
In [18]:
x=numpy.linspace(-1,1,1000)
In [19]:
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot(x,scipy.special.eval_jacobi(3,0,1,x))
plt.show()
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following expressions is fully explained on the corresponding section for this chapter in the book
In [29]:
(10**10)*scipy.special.psi(10**15)
Out[29]:
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following expressions is fully explained on the corresponding section for this chapter in the book
In [20]:
scipy.special.zeta(2,1)
Out[20]:
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following equation is fully explained on the corresponding section for this chapter in the book
In [21]:
import numpy
import scipy.special
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = (15.0, 10.0)
import mpl_toolkits.mplot3d
x=numpy.mgrid[-4:4:100j,-4:4:100j]
z=x[0]+1j*x[1]
(Ai, Aip, Bi, Bip) = scipy.special.airy(z)
steps = range(int(Bi.real.min()), int(Bi.real.max()),6)
fig=plt.figure()
subplot1=fig.add_subplot(121,aspect='equal')
subplot1.contourf(x[0], x[1], Bi.real, steps)
subplot2=fig.add_subplot(122,projection='3d')
subplot2.plot_surface(x[0],x[1],Bi.real)
plt.show()
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following equations is fully explained on the corresponding section for this chapter in the book
In [35]:
scipy.special.jn(5,scipy.pi)
Out[35]:
In [36]:
import scipy.interpolate
x=scipy.linspace(-1,1,10); xn=scipy.linspace(-1,1,1000)
y=scipy.sin(x)
polynomial=scipy.interpolate.lagrange(x, scipy.sin(x))
plt.plot(xn,polynomial(xn),x,y,'or')
plt.show()
To show extra details not shown in the book, the following lines of codes uses variables names slightly different from the ones in the code that appears in the book
In [58]:
import numpy
import scipy.interpolate
x1=numpy.linspace(1,10,10); y1=numpy.sin(x1)
Polynomial=scipy.interpolate.BarycentricInterpolator(x1,y1)
exactValues1=numpy.sin(x1+0.3)
exactValues1
Out[58]:
In [60]:
interpolatedValues1=Polynomial(x1+0.3)
interpolatedValues1
Out[60]:
In [61]:
PercentRelativeError1 = \
numpy.abs((exactValues1 - interpolatedValues1)/interpolatedValues1)*100
PercentRelativeError1
Out[61]:
In [62]:
x2=numpy.linspace(1.5,10.5,10); y2=numpy.sin(x2)
Polynomial.add_xi(x2,y2)
interpolatedValues=Polynomial(x1+0.3)
interpolatedValues
Out[62]:
In [64]:
PercentRelativeError = \
numpy.abs((exactValues1 - interpolatedValues)/interpolatedValues)*100
PercentRelativeError
Out[64]:
In [65]:
x3=numpy.sort(numpy.ravel([x1,x2]))
y3=numpy.sin(x3)
Polynomial3=scipy.interpolate.BarycentricInterpolator(x3,y3)
interpolatedValues3=Polynomial3(x1+0.3)
interpolatedValues3
Out[65]:
In [68]:
PercentRelativeError3 = \
numpy.abs((exactValues1 - interpolatedValues3)/interpolatedValues3)*100
PercentRelativeError3
Out[68]:
In [69]:
x=numpy.array([0,0,1,1,2,2]); y=numpy.array([0,0,1,0,2,0])
interp=scipy.interpolate.KroghInterpolator(x,y)
xn=numpy.linspace(0,2,20) # evaluate the polynomial in a larger set
plt.plot(x,y,'o',xn,interp(xn),'r')
plt.show()
In [70]:
x=numpy.arange(5); y=numpy.sin(x)
xn=numpy.linspace(0,4,40)
interp=scipy.interpolate.InterpolatedUnivariateSpline(x,y)
plt.plot(x,y,'.',xn,interp(xn))
plt.show()
In [71]:
import numpy
import scipy.interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
x=y=numpy.arange(10)
f=(lambda i,j: numpy.sin(i)*numpy.cos(j)) # function to interpolate
A=numpy.fromfunction(f, (10,10)) # generate samples
spline=scipy.interpolate.RectBivariateSpline(x,y,A)
fig=plt.figure()
subplot=fig.add_subplot(111,projection='3d')
xx=numpy.mgrid[0:9:100j, 0:9:100j] # larger grid for plotting
A=spline(numpy.linspace(0,9,100), numpy.linspace(0,9,100))
subplot.plot_surface(xx[0],xx[1],A)
plt.show()
In [26]:
import numpy
import scipy
import matplotlib.pyplot as plt
x=numpy.linspace(0,1,10)
y=numpy.sin(x*numpy.pi/2)
line=numpy.polyfit(x,y,deg=1)
plt.plot(x,y,'.',x,numpy.polyval(line,x),'r')
plt.show()
In [73]:
import numpy
import scipy.interpolate
import matplotlib.pyplot as plt
x=numpy.linspace(0,1,10)
y=numpy.sin(x*numpy.pi/2)
spline=scipy.interpolate.UnivariateSpline(x,y,k=2)
xn=numpy.linspace(0,1,100)
plt.plot(x,y,'.', xn, spline(xn))
plt.show()
In [74]:
x=None; y=None; yc=None
In [75]:
A=18; w=3*numpy.pi; h=0.5
x=numpy.linspace(0,1,100); y=A*numpy.sin(w*x+h)
plot1, = plt.plot(x, y, '-b', label="Data")
yc=None
yc=scipy.copy(y)
yc += 4*((0.5-scipy.rand(100))*numpy.exp(2*scipy.rand(100)**2)) # contamined data
plot2, = plt.plot(x, yc, 'r+', label="Contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
In [76]:
p0=None
p0 = [20, 2*scipy.pi, 1]
target_function = lambda x,AA,ww,hh: AA*scipy.sin(ww*x+hh)
In [77]:
import scipy.optimize
pF=None; pVar = None
pF,pVar = scipy.optimize.curve_fit(target_function, x, yc, p0)
print(pF)
In [78]:
yFit=None
yFit=target_function(x,*pF)
In [79]:
plot2, = plt.plot(x, yc, 'r+', label="Contamined Data")
plot3, = plt.plot(x, yFit,'k', label="Fit of contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
In [80]:
plot1, = plt.plot(x, y, '-b', label="Data")
plot3, = plt.plot(x, yFit,'--k', label="Fit of contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
In [81]:
plot1, = plt.plot(x, y, '-b', label="Data")
plot2, = plt.plot(x, yc, 'r+', label="Contamined Data")
plot3, = plt.plot(x, yFit,'--k', label="Fit of Contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
In [82]:
plt.rcParams['figure.figsize'] = (15.0, 15.0)
plt.subplot(2,2,1)
plt.plot(x, y, '-b', label="Data")
plt.plot(x, yc, 'r+', label="Contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=4, borderaxespad=0.)
plt.subplot(2,2,2)
plt.plot(x, yc, 'r+', label="Contamined Data")
plt.plot(x, yFit,'k', label="Fit of contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.subplot(2,1,2)
plt.plot(x, y, '-b', label="Data")
plt.plot(x, yc, 'r+', label="Contamined Data")
plt.plot(x, yFit,'--k', label="Fit of Contamined Data")
plt.legend()
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
Implementing the leastsq function as described in the corresponding section of the book
In [83]:
import numpy
import scipy
A=18; w=3*numpy.pi; h=0.5
x=None; y=None
x=numpy.linspace(0,1,100); y=A*numpy.sin(w*x+h)
y += 4*((0.5-scipy.rand(100))*numpy.exp(2*scipy.rand(100)**2))
import scipy.optimize
p0 = [20, 2*numpy.pi, 1]
target_function = lambda x,AA,ww,hh: AA*numpy.sin(ww*x+hh)
#pF,pVar = scipy.optimize.curve_fit(target_function, x, y, p0)
#print (pF)
In [84]:
error_function = lambda p,x,y: target_function(x,p[0],p[1],p[2])-y
lpF,lpVar = scipy.optimize.leastsq(error_function,p0,args=(x,y))
print (lpF)
In [85]:
import scipy.optimize
scipy.optimize.fmin(scipy.optimize.rosen,[0,0])
Out[85]:
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [86]:
help(scipy.optimize.minimize)
In [87]:
import scipy.special
print (scipy.special.jn_zeros(4,3))
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [88]:
import scipy.optimize
help(scipy.optimize.root)
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following equations is fully explained on the corresponding section for this chapter in the book
In [89]:
import numpy
import matplotlib.pyplot as plt
f=lambda x: [x[0]**2 - 2*x[0] - x[1] + 0.5, x[0]**2 + 4*x[1]**2 - 4]
x,y=numpy.mgrid[-0.5:2.5:24j,-0.5:2.5:24j]
U,V=f([x,y])
plt.quiver(x,y,U,V,color='r', \
linewidths=(0.2,), edgecolors=('k'), \
headaxislength=5)
plt.show()
In [90]:
import scipy.optimize
f=lambda x: [x[0]**2 - 2*x[0] - x[1] + 0.5, x[0]**2 + 4*x[1]**2 - 4]
In [91]:
scipy.optimize.root(f,[0,1])
Out[91]:
In [92]:
scipy.optimize.root(f,[2,0])
Out[92]:
General references for the following topics:
scipy.special
http://docs.scipy.org/doc/scipy-0.14.0/reference/special.html
scipy.integrate
http://docs.scipy.org/doc/scipy-0.14.0/reference/integrate.html#module-scipy.integrate
The NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following integrals is fully explained on the corresponding section for this chapter in the book
A general references for the following topics are:
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
Table of the Fresnel Sine and Cosine Integrals
http://www.mymathlib.com/functions/fresnel_sin_cos_integrals.html
The meaning of the following integrals is fully explained on the corresponding section for this chapter in the book
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following integrals is fully explained on the corresponding section for this chapter in the book
A general reference for the following topics is the
NIST Digital Library of Mathematical Functions
http://dlmf.nist.gov/
The meaning of the following integrals is fully explained on the corresponding section for this chapter in the book
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [93]:
import scipy.integrate
help(scipy.integrate.quad)
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [94]:
help(scipy.integrate.simps)
In [95]:
f=lambda t: numpy.exp(-t)*t**4
from scipy.special import gammainc
from scipy.integrate import quad
from scipy.misc import factorial
print (gammainc(5,1))
In [96]:
print('%.19f' % gammainc(5,1))
In [97]:
import numpy
result,error=quad(f,0,1)/factorial(4)
result
Out[97]:
In [98]:
import numpy
import scipy.integrate
x=numpy.linspace(0,1,10000)
scipy.integrate.simps(f(x)/factorial(4), x)
Out[98]:
The meaning of the following equation is fully explained on the corresponding section for this chapter in the book
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [99]:
import scipy.integrate
help(scipy.integrate.ode)
Let's solve via ode the following initial value problem (for additional details, pleae see the corresponding section for this chapter in the book)
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [100]:
import numpy
from scipy.integrate import ode
f=lambda t,y: -20*y # The ODE
actual_solution=lambda t:numpy.exp(-20*t) # actual solution
dt=0.01 # time step
solver=ode(f).set_integrator('dop853') # solver
solver.set_initial_value(1,0) # initial value
while solver.successful() and solver.t<=1+dt:
# solve the equation at succesive time steps,
# until the time is greater than 1
# but make sure that the solution is successful
print (solver.t, solver.y, actual_solution(solver.t))
# We compare each numerical solution with the actual
# solution of the ODE
solver.integrate(solver.t + dt) # solve next step
In [100]:
Click the left mouse button on the left of the output of the following command to shorten the displayed output in a elevator type window
In [101]:
help(scipy.integrate.odeint)
The meaning of the following equations is fully explained on the corresponding section for this chapter in the book
In [102]:
import numpy
from numpy import linspace
import scipy
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
sigma=10.0
b=8.0/3.0
r=28.0
f = lambda x,t: [sigma*(x[1]-x[0]),
r*x[0]-x[1]-x[0]*x[2],
x[0]*x[1]-b*x[2]]
t=linspace(0,20,2000); y0=[5.0,5.0,5.0]
solution=odeint(f,y0,t)
X=solution[:,0]; Y=solution[:,1]; Z=solution[:,2]
import matplotlib.pyplot as plt
plt.gca(projection='3d'); plt.plot(X,Y,Z)
plt.show()
In [103]:
plt.rcParams['figure.figsize'] = (15.0, 5.0)
plt.subplot(121); plt.plot(t,Z)
plt.subplot(122); plt.plot(Y,Z)
plt.show()
Content under Creative Commons Attribution license CC-BY 4.0, code under MIT license (c)2014 Sergio Rojas (srojas@usb.ve) and Erik A Christensen (erikcny@aol.com).