Sie sind auf Seite 1von 7

Scipy. Notes 10.

Yves Semegni October 13, 2011

Scipy - Numpy Linear algebra, Roots nding, Numerical integrations and differential equations
Linear equations

1.1

The solution is

Solving linear systems of equations is straightforward using the numpy submodule linalg.solve Example: Solve the following system of linear equations x + 3y + 5z = 10 2x + 5y + z = 8 2x + 3y + 8z = 3 1 232 9.28 x 1 3 5 10 y = 2 5 1 8 = 1 129 = 5.16 25 19 0.76 z 2 3 8 3 >>> import numpy as np >>> import np.linalg >>> A = np.mat([1,3,5; 2,5,1; 2,3,8]) >>> b = np.mat([10;8;3]) >>> np.linalg.det(A) -25.000000000000004 The determinant of A is not 0, so there is a unique solution >>> np.linalg.solve(A, b) matrix([[-9.28], [ 5.16], [ 0.76]])

1.2

Root nding

To nd the roots of a polynomial, used the numpy roots subroutine. Example 1: Find the roots of the polynomial x3 3x2 + 2x 1 >>> import numpy as np >>> p = [1,-3,2,-1] >>> np.roots(p) array([ 2.32471796+0.j, 0.33764102+0.56227951j, 0.33764102-0.56227951j]) To nd the roots of a non-linear equations, use the bissection method implemented in the scipy submodule optimize.bisect or the Newton-Raphson method implemented in the scipy submodule optimize.newton. Example 2. Find the roots of the equation equation x + 2cos(x) = 0 1

Bissection method starting on the interval [-2, 2] >>> import scipy >>> import scipy.optimize >>> def f(x): y = x + 2*scipy.cos(x) return y >>> scipy.optimize.bisect(f, -2, 2) -1.0298665293221347 # starting interval [-2, 2]

Newton Raphson method with starting points at x0 = 2. >>> import scipy >>> import scipy.optimize >>> def f(x): y = x + 2*scipy.cos(x) return y >>> scipy.optimize.newton(f, 2) -1.0298665293222757 To nd a root of a set of non-linear equations, the scipy submodule optimize.fsolve is needed. Example 3: Find the roots of the single-variable equation x +2cos(x) = 0 using fsolve at starting point 0.3 >>> import scipy >>> import scipy.optimize >>> def f(x): y = x + 2*cos(x) return y >>> x0 = scipy.optimize.fsolve(f, 0.3) >>> print x0, f(x0) -1.0298665293 # 0.3 is the starting point # starting point x0 = 2, #xn+1 = xn - f(xn)/f(xn) for n>0

Example 4: Find the solution of the system of non-linear equations x0 cos(x1 ) = 4 x0 x1 x1 = 5 starting at x0 = 1 and x1 = 1 using fsolve >>> import scipy >>> import scipy.optimize >>> def func2(x): y = [x[0]*cos(x[1]) - 4, x[1]*x[0] - x[1] - 5] 2

return y >>> x0 = scipy.optimize.fsolve(func2, [1, 1]) >>> print x0 [ 6.5041, 0.9084] Python oers an alternative way of dening a function using the lambda form. The lambda form allows to create a function object. Example 5: Solve the system on non-linear equations x**2 - 2*x*y = z, x*y + y**2*z = 0, starting at x=1, y = -1, z =2 >>> import scipy >>> import scipy.optimize >>> f = lambda x: [x[0]**2 - 2*x[0]*x[1] - x[2], x[0]*x[1] + x[1]**2*x[2], x[2]*x[0] - x[1]*x[2]+ x[0] - 1] >>> x0 = scipy.optimize.fsolve(f, [1, -1, 2]) >>> print x0 [ 0.38196601, -0.61803399, 0.61803399] z*x - y*z+ x = 1

1.3

Integration

The integrate function provides several integration techniques including an ordinary dierential equation integrator. 1.3.1 Integration of Polynomials

Integrate p = (x5 4x3 2x2 3x + 2)5 from 0 to 1 >>> import numpy as np >>> pol = np.poly1d([1, 0, -4, -2, -3, 2])**5 >>> polint = pol.integ() >>> print polint(1) - polint(0) -579.48595177 1.3.2 >>> >>> >>> >>> Numerical integration: the scipy.integrate module

import scipy as sp import sp.integrate help(sp.integrate) dir(sp.integrate)

# get help # list the functions available

Methods for Integrating Functions odeint quad dblquad tplquad gauss_quad #Integrate ordinary differential equations. #General purpose integration. #General purpose double integration. #General purpose triple integration. #Integrate func(x) using Gaussian quadrature of order n. 3

The function scipy.integrate.quad provides a mean to integrate a function of one variable between two points. The points can be ( integrate.inf ) to indicate innite limits. 2 8 3 2 Example 1: Compute A = 0 x2 dx. The exact value of A is: A = 1 3 x 0 = 3 2.6666. Here are the steps to nd the numerical solution >>> import scipy.integrate >>> def func(x): y = x**2 return y >>> result, error = scipy.integrate.quad(func, 0.0, 2) >>> result 2.666666666666667 >>> error 2.960594732333751e-14) Example 2: Compute A =
1 0 e 2x

#numerical solution and error

dx. The exact solution is 2

>>> import scipy.integrate >>> import math >>> y = lambda x: math.exp(-0.5*x) >>> result, error = scipy.integrate.quad(y, 0, scipy.inf) >>> result 2.0 >>> error 7.161469913133811e-11 Example 3: Suppose you wish to integrate the bessel function jv(2.5, x) along the interval [0, 4.5]
4.5

I=
0

J2.5 (x) dx

>>> import scipy.integrate >>> import scipy.special >>> y = lambda x: scipy.special.jv(2.5,x) >>> result, error = scipy.integrate.quad(y, 0, 4.5) >>> print result 1.1178179380783249 >>> print error 7.8663172481899801e-09) 1.3.3 Double integration
2 1 x2 1 0 y

Example 1: (DoubleIntegrationDemo.py) Compute the integral

dxdy

"""double integration""" from __future__ import division import scipy import scipy.integrate def f(x,y): 4 #always use this to avoid integer division

s = x**2/y return s if __name__ == __main__: result, error = scipy.integrate.dblquad(lambda y , x: f(x,y), 0, 1, lambda y: 1, lambda y: 2) print \n print Result =,result print Error =, error Example 2: (DoubleIntegration.py) Compute the integral I = exact value is I = 1 3
ext 0 1 x3

dxdy The

""" Double integration """ from __future__ import division import scipy import scipy.integrate def func(x,t): y = scipy.exp(-x*t) / t**3 return y if __name__ == __main__:

result, error = scipy.integrate.dblquad(lambda t, x: func(x,t), 0, scipy.Inf, lambda t: 1, lambda t: scipy.Inf) print \n print Result =,result print Error =, error

1.4

Ordinary dierential equations: the scipy.integrate.odeint function


dx dt

Example: Exponential decay. Solve """ Numerical solution of

= x with initial condition x0 = 2

ordinary differential equation """

# import modules for solving import scipy import scipy.integrate # import module for plotting import pylab as pl 5

def dx_dt(x, t=0): y = -x return y if __name__ == "__main__":

# specify the initial time point t0=0

t = scipy.linspace(0, 6, 1000) # create 1000 time points stating at t0=0 x0 = 2 # initial condition dx_over_dt = scipy.integrate.odeint(dx_dt, x0, t) # solve using odeint

pl.plot(t, dx_over_dt) pl.show() Example: Exact versus approximated solution. Solve the non-linear rst order equation dy dt = 2 (1 2t)y with boundary condition y 0 = 1. Plot the curves of the exact solution f (t) = t2 1 t+1 and the approximated solution obtained with the function odeint. """ Numerical solution of ordinary differential equation. Exact versus approximated solution""" # import modules for solving import scipy import scipy.integrate # import module for plotting import pylab as pl def dy_dt(y, t=0): z = (1 - t)*y**2 return z def f_exact(t): y = 1.0/(t**2 -t+1) return y if __name__ == "__main__": t = scipy.linspace(0, 10, 1000) # create 1000 time points stating at t0=0 y0 = 1 # initial condition y_approx = scipy.integrate.odeint(dy_dt, y0, t) # solve using odeint f = scipy.vectorize(f_exact) y_exact = f(t) # print len(y_approx), len(y_exact) # print scipy.shape(y_exact), scipy.shape(y_approx[:,0]) pl.plot(t, y_approx[:,0], ro, t,y_exact , bx) pl.legend([Approximated solution,Exact solution]) 6 # specify the initial time point t0=0

#exact solution starting at y0=1

pl.savefig(ExactVersusApprox.png) pl.show() Example: System of non-linear rst order dierential equations. Solve the following system non-linear rst order Lokta Volterra equations
dx dt dy dt

= x 0.1xy = 2 5 y + 0.7xy

with boundary condition x0 = 10, y 0 = 5. Plot the curves of x(t) and y(t) on the same graph for t in the interval [0,15] """ Numerical solution of system of first order ordinary differential equations """

# import modules for solving import scipy import scipy.integrate # import module for plotting import pylab as pl def dX_dt(X, t=0): y = scipy.array([ X[0] return y if __name__ == "__main__": t = scipy.linspace(0, 15, 1000) # create 1000 time points stating at t0=0 # specify the initial time point t0=0 0.1*X[0]*X[1] , -2./5*X[1] + 0.7*X[0]*X[1] ])

X0 = scipy.array([10, 5]) # initials conditions: x0=10 and y0=5 X, infodict = scipy.integrate.odeint(dX_dt, X0, t, full_output=True) # infodict[message] #Integration successful. pl.plot(t, X[:,0],ro, t, X[:,1], bx) # x = X[:,0] and y = X[:,1] pl.legend([x(t),y(t)]) pl.plot(X[:,0], X[:,1]) # plot phase portrait pl.show() Exercises 1.

Das könnte Ihnen auch gefallen