Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programmazione ad alto livello con Python

Similar presentations


Presentation on theme: "Programmazione ad alto livello con Python"— Presentation transcript:

1 Programmazione ad alto livello con Python
Lezione 8: Introduzione alla libreria per il calcolo scientifico SciPy. Dr. Gabriele Mencagli Dipartimento di Informatica Università di Pisa 21/09/2018

2 Informazioni Dr. Gabriele Mencagli
Dipartimento di Informatica, Università di Pisa Stanza 287. Ricevimento su appuntamento (mandare una ) web: Organizzazione: corso introduttivo. 16 ore di didattica frontale, 14 di esercizi individuali in laboratorio Durata: 2 mesi Modalità di esame: progetto finale di complessità variabile Importante gli homework!!! (tipicamente uno per settimana) 21/09/2018

3 Available at: http://www.spipy.org
What is SciPy? SciPy is a collection of mathematical algorithms and convenience functions built on the NumPy extension of Python. The additional benefit of basing SciPy on Python is that this also makes a powerful programming language available for use in developing sophisticated programs and specialized applications. Scientific applications using SciPy benefit from the development of additional modules in numerous niche’s of the software landscape by developers across the world. Everything from parallel programming to web and data-base subroutines and classes have been made available to the Python programmer. All of this power is available in addition to the mathematical libraries in SciPy. During this lecture we will see the main features of SciPy, its structures, the set of functionalities provided to the user and how to program with SciPy! Available at: 21/09/2018

4 SciPy organization SciPy library is organized into packages (modules) covering different scientific computing domains. These are summarized in the following table: SciPy is fully integrated with other libraries that we have already studied during this cource, notably: NumPy (with ndarrays) and MatPlotLib! 21/09/2018

5 Documentation SciPy and NumPy have documentation versions in both HTML and PDF format available at that cover nearly all available functionality. However, this documentation is still work-in-progress and some parts may be incomplete or sparse. Python’s documentation strings are used in SciPy for on-line documentation. There are two methods for reading them and getting help: One is Python’s command help in the pydoc module. Entering this command with no arguments (i.e. >>> help ) launches an interactive help session that allows searching through the keywords and modules available to all of Python. Secondly, running the command help(obj) with an object as the argument displays that object’s calling signature, and documentation string. Let us show and example of how to read the SciPy documentation about objects, methods and functions. 21/09/2018

6 Documentation (2) An example of pydoc command help. You can use it for any function of an imported module: 21/09/2018

7 Helpful sites Two important web sites in which interested readers can find useful information about NumPy and SciPy: SCIPY DOCUMENTATION NUMPY EXAMPLES 21/09/2018

8 Useful import SciPy builds on NumPy, and for all basic array handling needs you can use NumPy functions: To use functions from some of the SciPy modules, you can do: The top level of SciPy also contains functions from NumPy and numpy.lib.scimath. However, it is better to use them directly from the NumPy module instead. Remember to install SciPy and NumPy: sometimes, they are not already installed! >>> import numpy as np >>> np.some_function() >>> from scipy import some_module >>> some_module.some_function() 21/09/2018

9 Vectorized functions One of the features that NumPy provides is a class vectorize to convert an ordinary Python function which accepts scalars and returns scalars into a “vectorized-function”. 21/09/2018

10 Polynomial p = poly1d(<coefficient array>)
p.roots (p.r) are the roots p.coefficients (p.c) are the coefficients p.order is the order p[n] is the coefficient of xn p(val) evaulates the polynomial at val p.integ() integrates the polynomial p.deriv() differentiates the polynomial Basic numeric operations (+,-,/,*) work Acts like p.c when used as an array Fancy printing >>> import numpy as np >>> p = np.poly1d([1,-2,4]) >>> print p 2 x - 2 x + 4 >>> g = p**3 + p*(3-2*p) >>> print g x - 6 x + 25 x - 51 x + 81 x - 58 x + 44 >>> print g.deriv(m=2) #m=order 30 x x x x + 162 >>> print p.integ(m=2,k=[2,1]) x x + 2 x + 2 x + 1 >>> print p.roots [ j j] >>> print p.coeffs [ ] 21/09/2018

11 Polynomial (2) To use polynomial in SciPy we rely on the NumPy library. The most common way is to use the poly1d class from NumPy. This class accepts coefficients or polynomial roots to initialize a polynomial. 21/09/2018

12 Finding the roots An example in which we use SciPy, NumPy and MatPlotLib altogether to show the curve of a polynomial and its real roots! >>> import numpy as np >>> import matplotlib.pyplot as plt >>> p = np.poly1d([1.3, 4.0, 0.6]) >>> print p 2 1.3 x + 4 x + 0.6 >>> x = np.linspace(-4, 1.0, 101) >>> y = p(x) >>> plt.plot(x,y,'-') >>> r = p.roots >>> s = p(r) >>> r array([ , ]) >>> plt.plot(r.real,s.real,'ro') >>> plt.show() 21/09/2018

13 Interpolation 1-D Interpolating Class
SciPy provides great support to interpolation with 1-D and 2-D functions. scipy.interpolate --- General purpose Interpolation 1-D Interpolating Class Constructs callable function from data points and desired spline interpolation order. Function takes vector of inputs and returns interpolated value using the spline. 1-D and 2-D spline interpolation (FITPACK) Smoothing splines up to order 5. Parametric splines. 21/09/2018

14 1-D interpolation The standard function for 1-D interpolation can be imported by using: The function has the following signature: Returns a function that uses interpolation to find the value of new points: x – 1-D array of increasing real values which cannot contain duplicates; y – Ndarray of real values whose length along the interpolation axis must be len(x); kind – kind of interpolation (e.g. ‘linear’, ‘quadratic’, ‘cubic’). Can also be an integer n>1 which returns interpolating spline (with minimum sum-of-squares discontinuity in nth derivative); axis – axis of y along which to interpolate; copy – make internal copies of x and y; bounds_error – raise error for out-of-bounds; fill_value – if bounds_error is False, then use this value to fill in out-of-bounds. >>> from scipy.interpolate import interp1d interp1d(x, y, kind=‘linear’, axis=-1, copy=True, bounds_error=True, fill_value=numpy.nan) 21/09/2018

15 1-D interpolation example
An example of 1-D interpolation with results shown graphically using MatPlotLib. We show the use of spline interpolation (multi-polynomial). >>> from scipy.interpolate import interp1d >>> import matplotlib.pyplot as plt >>> import numpy as np # Sample values. >>> x = np.linspace(0, 2*np.pi, 6) >>> y = np.sin(x) # Create a spline class for interpolation. # kind=5 sets to 5th degree spline. # kind=‘linear’ -> linear interpolation. # kind=n -> use an nth order spline. >>> spline_fit = interp1d(x, y, kind=5) >>> xx = np.linspace(0, 2*np.pi, 50) >>> yy = spline_fit(xx) # Display the results. >>> plt. plot(xx, np.sin(xx), 'r-', x, y, 'ro', xx, yy, 'b--', linewidth=2) >>> plt.show() 21/09/2018

16 1-D interpolation example (2)
Another example of 1-D interpolation (linear and cubic): 21/09/2018

17 Linear algebra Uses ATLAS if available --- very fast
SciPy provides a set of advanced functions for supporting linear algebra computations. scipy.linalg --- FAST LINEAR ALGEBRA Uses ATLAS if available --- very fast Low-level access to BLAS and LAPACK routines in modules linalg.fblas, and linalg.flapack (FORTRAN order) High level matrix routines Linear Algebra Basics: inv, solve, det, norm, lstsq, pinv Decompositions: eig, lu, svd, orth, cholesky, qr, schur Matrix Functions: expm, logm, sqrtm, cosm, coshm, funm (general matrix functions) 21/09/2018

18 Linear algebra basics Some basic functionalities of linear algebra kernels in SciPy: LU FACTORIZATION EIGEN VALUES AND VECTORS >>> import numpy as np >>> from scipy import linalg >>> a = np.array([[1,3,5], [2,5,1], [2,3,6]]) # Time consuming factorization. >>> lu, piv = linalg.lu_factor(a) # Fast solve for 1 or more right hand sides. >>> b = np.array([10,8,3]) >>> linalg.lu_solve((lu, piv), b) array([ , , ]) >>> import numpy as np >>> from scipy import linalg >>> a = np.array([[1,3,5], [2,5,1], [2,3,6]]) # Compute eigen values/vectors. >>> vals, vecs = linalg.eig(a) # Print eigen values. >>> vals array([ j, j, j]) # Eigen vectors are in columns print first eigen vector. >>> vecs[:,0] array([ , , ]) Matrix LU contains U in its upper triangle and L in its lower triangle. Piv is the permutation matrix 21/09/2018

19 Matrix objects Solving linear system of equations in SciPy:
STRING CONSTRUCTION DIAGONAL >>> import numpy as np >>> a = np.mat('[1,3,5;2,5,1;2,3,6]') >>> a matrix([[1, 3, 5], [2, 5, 1], [2, 3, 6]]) >>> a.diagonal() matrix([[1, 5, 6]]) SOLVE >>> b = np.mat('10;8;3') >>> a.I*b matrix([[ ], [ ], [ ]]) >>> from scipy import linalg >>> linalg.solve(a,b) TRANSPOSE ATTRIBUTE >>> a.T matrix([[1, 2, 2], [3, 5, 3], [5, 1, 6]]) INVERTED ATTRIBUTE >>> a.I matrix([[ , , ], [ , , ], [ , , ] ]) 21/09/2018

20 Optimization SciPy provides great support to several optimization methods. scipy.optimize --- unconstrained minimization and root finding Unconstrained Optimization fmin (Nelder-Mead simplex), fmin_powell (Powell’s method), fmin_bfgs (BFGS quasi-Newton method), fmin_ncg (Newton conjugate gradient), leastsq (Levenberg-Marquardt), anneal (simulated annealing global minimizer), brute (brute force global minimizer), brent (excellent 1-D minimizer), golden, bracket Constrained Optimization fmin_l_bfgs_b, fmin_tnc (truncated newton code), fmin_cobyla (constrained optimization by linear approximation), fminbound (interval constrained 1-d minimizer) Root finding fsolve (using MINPACK), brentq, brenth, ridder, newton, bisect, fixed_point (fixed point equation solver) 21/09/2018

21 1-D minimization An example of minimization of a 1-D function (Bessel’s function in this case): EXAMPLE: MINIMIZE BESSEL FUNCTION >>> from scipy.special import j1 >>> from scipy.optimize import \ Fminbound >>> import numpy as np >>> import matplotlib.pyplot as plt # Minimize 1st order bessel function between 4 and 7. >>> x=np.arange(2, 7.1, 0.1) >>> j1x = j1(x) >>> plt.plot(x,j1x,’-’) >>> x_min = fminbound(j1,4,7) >>> j1_min = j1(x_min) >>> plt.plot([x_min],[j1_min],’ro’) >>> plt.show() By default fminbound uses Brent’s method! 21/09/2018

22 Fitting polynomials Polyfit returns the coefficients of a polynomial of degree deg that is the least squares fit to the data values y given at points x. POLYFIT(X, Y, DEGREE) >>> from numpy import polyfit, poly1d >>> from scipy.stats import norm >>> import numpy as np # Create clean data. >>> x = np.linspace(0, 4.0, 100) >>> y = 1.5 * np.exp(-0.2 * x) + 0.3 # Add a bit of noise. >>> noise = 0.1 * norm.rvs(size=100) >>> noisy_y = y + noise # Fit noisy data with a linear model. >>> linear_coef = polyfit(x, noisy_y, 1) >>> linear_poly = poly1d(linear_coef) >>> linear_y = linear_poly(x) # Fit noisy data with a quadratic model. >>> quad_coef = polyfit(x, noisy_y, 2) >>> quad_poly = poly1d(quad_coef) >>> quad_y = quad_poly(x)) 21/09/2018

23 Signal processing What’s Available?
SciPy provides an entire module for signal processing operations performed on Ndarrays: scipy.signal --- Signal and Image Processing What’s Available? Filtering General 2-D Convolution (more boundary conditions) N-D convolution B-spline filtering N-D Order filter, N-D median filter, faster 2d version, IIR and FIR filtering and filter design LTI systems System simulation Impulse and step responses Partial fraction expansion 21/09/2018

24 Image processing Many signal processing filters are available in SciPy. They can be applied on images and consist in well-known filtering techniques as in this example: NOISY IMAGE FILTERED IMAGE noise removal filter IMAGE DETECT EDGES edge detection 21/09/2018

25 Open an image SciPy offers a module to manipulate images. You can open an image file and modify it by using proper filters. >>> from scipy import misc >>> import numpy as np >>> import matplotlib.pyplot as plt >>> img = misc.lena() >>> misc.imsave('lena.png’) >>> plt.imshow(img) >>> plt.show() >>> # We can also create a ndarray of the image. >>> lena = misc.imread('lena.png’) >>> type(lena) <type 'numpy.ndarray'> >>> lena.shape, lena.dtype ((512, 512), dtype('uint8')) Lena.png is a 512x512 image file with grayscale! 21/09/2018

26 Image tansformations Now we can manipulate the open image. Several geometrical transformations are possible in SciPy: >>> from scipy import misc >>> from scipy import ndimage >>> import numpy as np >>> import matplotlib.pyplot as plt >>> lena = misc.lena() >>> # 512 x 512. >>> lx, ly = lena.shape >>> # Cropping. >>> crop_lena = lena[lx/4:-lx/4, ly/4:-ly/4] >>> # up <-> down flip. >>> flip_ud_lena = np.flipud(lena) >>> # rotation. >>> rotate_lena = ndimage.rotate(lena, 45) >>> rotate_lena_noreshape = ndimage.rotate(lena, 45, reshape=False) 21/09/2018

27 Image filtering The image can be modified by applying several filtering techniques available in the SciPy library! Filters usually place the value of pixels by a function of the values of neighboring pixels. >>> from scipy import misc >>> lena = misc.lena() >>> # Gaussian filter. >>> blurred_lena = ndimage.gaussian_filter(lena, sigma=3) >>> very_blurred = ndimage.gaussian_filter(lena, sigma=5) >>> # Uniform filter. >>> local_mean = ndimage.uniform_filter(lena, size=11) 21/09/2018

28 Feature extraction Feature extraction are a set of advanced filters able to extract interesting features from an image. A notable example is edge detection: >>> from scipy import misc >>> from scipy.ndimage.filters import sobel >>> import numpy as np >>> import matplotlib.pyplot as plt >>> img = misc.lena() >>> misc.imsave('lena.png', l) >>> plt.imshow(img) >>> plt.show() >>> # We apply Sobel (Edge Detection). >>> edges = sobel(lena) >>> plt.imshow(edges) 21/09/2018

29 Integration Ordinary Differential Equations (ODE)
SciPy offers several methods to perform numerical integration. scipy.integrate --- General purpose Integration Ordinary Differential Equations (ODE) integrate.odeint, integrate.ode Samples of a 1-d function integrate.trapz (trapezoidal Method), integrate.simps (Simpson Method), integrate.romb (Romberg Method) Arbitrary callable function integrate.quad (general purpose), integrate.dblquad (double integration), integrate.tplquad (triple integration), integrate.fixed_quad (fixed order Gaussian integration), integrate.quadrature (Gaussian quadrature to tolerance), integrate.romberg (Romberg) 21/09/2018

30 Integration example Integrate func from a to b (possibly infinite interval) using a technique from the Fortran library QUADPACK A simple example of integration in which the function is given by the programmer. EXAMPLE (INTEGRATE A CALLABLE) >>> import numpy as np >>> from scipy import integrate # Compare sin to integral(cos) >>> def func(x): return integrate.quad(np.cos,0,x)[0] >>> vecfunc = vectorize(func) >>> x = np.linspace(0, 2*np.pi, 100) >>> x2 = x[::5] # Only 20 points. >>> y = np.sin(x) >>> y2 = vecfunc(x2) >>> plot(x,y,x2,y2,'rx') >>> legend([‘Exact‘, ‘Integral Result’]) 21/09/2018

31 MatLab compatibility You may have a .mat file that you want to read into SciPy. Or, you want to pass some variables from SciPy/NumPy into MatLab. In these examples we use Octave which is a free version of MatLab. 21/09/2018

32 MatLab compatibility (2)
In Python (with SciPy and NumPy) we can open a MatLab file and inspect its content. We need to use import scipy.io as sio. Arrays and matrices saved in the MatLab file can be imported and traslated into corresponding Ndarrays! 21/09/2018

33 From Python to MatLab We can also do the opposite (from Python to MatLab): An in MatLab (octave) we can do: 21/09/2018

34 PyLab! IPython SciPy Matplotlib NumPy Python
You could often listen to the name PyLab when searching information about Python libraries for scientific computing. Sometimes the union of the 5 packages is called PyLab ipython -pylab. Literally 1000's more modules/packages for Python PMV PIL IPython MayaVi VTK SciPy Matplotlib DejaVu RPy PMV NumPy ETS ViPEr Python MolKit Pygame 21/09/2018

35 END 21/09/2018

36 Special functions Includes over 200 functions:
The module scipy.special includes many functions not defined in standard modules like math, numpy, etc. scipy.special Includes over 200 functions: Airy, Elliptic, Bessel, Gamma, Hyper-Geometric, Struve, Error, Orthogonal Polynomials, Parabolic Cylinder, Mathieu, Spheroidal Wave, Kelvin FIRST ORDER BESSEL EXAMPLE >>> import numpy as np >>> from scipy import special >>> import matplotlib.pyplot as plt >>> x = np.linspace(0, 100, 1001) # An example of ipergeometrical eq. >>> j0x = special.j0(x) >>> plt.plot(x,j0x) Bessel’s function of the first kind with order 1 21/09/2018

37 Special functions (2) Another example of special function already implemented in SciPy: Airy’s functions. They are the solutions of special ODEs. AIRY FUNCTIONS >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import special >>> x = np.linspace(-5, 1.5, 100) >>> Ai, Aip, Bi, Bip = special.airy(x) >>> plt.plot(x, Ai) # derivative of Ai. >>> plt.plot(x, Aip) >>> plt.plot(x, Bi) # derivative of Bi. >>> plt.plot(x, Bip) 21/09/2018

38 interp2d(x, y, z, kind=‘linear’)
2-D interpolation The standard function for 2-D interpolation can be imported by using: The function has the following signature: Returns a function, f, that uses interpolation to find the value of new points: z_new = f(x_new, y_new): x – 1-D or 2-D array; y – 1-D or 2-D array; z – 1-D or 2-D array representing function evaluated at x and y; kind – kind of interpolation: ‘linear’, ‘quadratic’, or ‘cubic’; The shape of x, y, and z must be the same. >>> from scipy.interpolate import interp2d interp2d(x, y, z, kind=‘linear’) 21/09/2018

39 Continuous statistics
SciPy offers an entire package for continuous statistics. scipy.stats CONTINUOUS DISTRIBUTIONS Over 80 continuous distributions! METHODS pdf cdf rvs ppf stats fit sf isf entropy nnlf moment freeze 21/09/2018

40 Discrete statistics SciPy offers an entire package for discrete statistics. scipy.stats Discrete Distributions 10 standard discrete distributions (plus any finite RV) METHODS pmf cdf rvs ppf stats sf isf moment entropy freeze 21/09/2018

41 Using stats object An example of how to use a stat object in SciPy to inspect a set of samples and extract interesting statistical properties and measures: >>> import numpy as np >>> from scipy.stats import norm >>> x = np.linspace(-5, 5, 100) # Calculate probability dist. >>> pdf = norm.pdf(x) # Calculate cummulative dist. >>> cdf = norm.cdf(x) # Calculate Percent Point Function >>> ppf = norm.ppf(x) # Estimate parameters from data. # Sample normal dist. 100 times. >>> samp = norm.rvs(size=100) >>> mu, sigma = norm.fit(samp) >>> print "%4.2f, %4.2f" % (mu, sigma) -0.14, 1.01 21/09/2018

42 Using stats object (2) Example of discrete statistic distributions using the stats object of SciPy: CREATING NEW DISCRETE DISTRIBUTIONS >>> import matplotlib.pyplot as plt >>> import numpy as np >>> from scipy.stats import rv_discrete # Create loaded dice. >>> xk = [1,2,3,4,5,6] >>> pk = [0.3,0.35,0.25,0.05, 0.025,0.025] >>> new = rv_discrete(name='loaded', values=(xk,pk)) # Calculate histogram. >>> samples = new.rvs(size=1000) >>> bins=np.linspace(0.5,5.5,6) >>> plt.subplot(211) >>> plt.hist(samples,bins=bins,normed=True) # Calculate pmf. >>> x = np.range(0,8) >>> plt.subplot(212) >>> plt.stem(x,new.pmf(x)) >>> plt.show() 21/09/2018

43 More on statistics SciPy offers powerful tools to estimate a continuous distribution from a set of raw data. CONTINOUS DISTRIBUTION ESTIMATION USING GAUSSIAN KERNELS >>> import matplotlib.pyplot as plt >>> import numpy as np >>> import scipy.stats as stats >>> from scipy.stats.kde import gaussian_kde # Sample two normal distributions and create a bi-modal distribution. >>> rv1 = stats.norm() >>> rv2 = stats.norm(2.0,0.8) >>> samples = np.hstack([rv1.rvs(size=100), rv2.rvs(size=100)]) # Use a gaussian kernel density to estimate the pdf for the samples. >>> approximate_pdf = gaussian_kde(samples) >>> x = np.linspace(-3,6,200) # Compare the histogram of the samples to the pdf approximation. >>> plt.hist(samples, bins=25, normed=True) >>> plt.plot(x, approximate_pdf(x),’r’) >>> plt.show() 21/09/2018

44 Iterative methods An example of the conjugate gradient method applied on the minimization of the Rosenbrock function: 21/09/2018

45 Iterative methods (2) By passing explicitly the gradient we can greatly reduce the number of iterations! 21/09/2018

46 Data fitting Minimizzare la somma dei quadrati degli scarti.
A class of optimization problems is represented by least squares problems in which we are looking for a solution the minimizes the sum of the squares of the errors. NONLINEAR LEAST SQUARES >>> from scipy.optimize import leastsq >>> import numpy as np # Define the function to fit. >>> def function(x, a , b, f, phi): result = a * np.exp(-b * np.sin(f * x + phi)) return result # And an error function that compares it to data. >>> def error_function(params, x_data, y_data): result = func(x_data, *params) – y_data # Create a noisy data set. >>> actual_params = [3, 2, 1, pi/4] >>> x = np.linspace(0,2*pi,25) >>> exact = function(x, *actual_params) >>> noisy = exact * np.random.randn(len(x)) # Use least squares to to estimate the function parameters from the noisy data. >>> initial_guess = [1,1,1,1] >>> estimated_params, d = leastsq(error_function, initial_guess, args=(x, noisy)) >>> estimated_params array([3.1705, , , ]) 21/09/2018

47 Integrating with trapz.
Several numerical integration methods are available in the scipy.integrate module. In this example we show the use of the trapezoidal rule to compute integral from samples. >>> import numpy as np >>> from scipy.integrate import trapz >>> import matplotlib.pyplot as plt # Compare sin to integral(cos). >>> x = np.linspace(0, 2*np.pi, 100) >>> y = sin(x) >>> fx = cos(x) >>> N = len(x)+1 >>> y2 = [trapz(fx[:i],x[:i]) for i in range(5,N,5)] >>> x2 = x[4::5] >>> plt.plot(x,y,x2,y2,'rx') >>> plt.legend([‘Exact‘, ‘Trapezoidal Rule’]) >>> plt.show() 21/09/2018

48 Integrating with samples
For an odd number of samples that are equally spaced Simpson’s rule is exact if the function is a polynomial of order 3 or less. If the samples are not equally spaced, then the result is exact if the function is a polynomial of order 2 or less. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.integrate import simps >>> def f(x): return x**2 >>> def f2(x): return x**3 >>> x = np.array([1,3,4]) >>> y1 = f1(x) >>> I1 = integrate.simps(y1, x) >>> print(I1) 21.0 >>> y2 = f2(x) >>> I2 = integrate.simps(y2, x) >>> print(I2) 61.5 21/09/2018

49 Ordinary differential equations
It includes the function odeint for numerically solving sets of first-order, ordinary differential equations (ODEs) using sophisticated algorithms. The example below calculates the solution to the following second-order differential equation: It can be rewritten as the following two first-order differential equations: The function y and its derivative y′will be part of elements of an array. The function y is the first element y[0] and the derivative y′is y[1]. 21/09/2018

50 Ordinary differential equations (2)
We can solve numerically the previous differential equations using the tools provided by SciPy. As in this example: >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.integrate import odeint # Return the first derivative of each element of y. >>> def deriv(y,t): ... a = -2.0 ... b = -0.1 ... return np.array([y[1], a*y[0]+b*y[1]]) >>> time = np.linspace(0.0,10.0,1000) # initial values. >>> yinit = np.array([0.0005,0.2]) >>> y = odeint(deriv,yinit,time) >>> plt.figure() >>> plt.plot(time,y[:,0]) >>> plt.xlabel(‘t’) >>> plt.ylabel(‘y’) >>> plt.show() 21/09/2018


Download ppt "Programmazione ad alto livello con Python"

Similar presentations


Ads by Google