Hướng dẫn how do you write an integral code in python? - làm thế nào để bạn viết một mã tích phân trong python?

Tổng quan¶

Ngôn ngữ Python cốt lõi (bao gồm các thư viện tiêu chuẩn) cung cấp đủ chức năng để thực hiện các nhiệm vụ nghiên cứu tính toán. Tuy nhiên, có các thư viện Python dành riêng (bên thứ ba) cung cấp chức năng mở rộng

  • Cung cấp các công cụ số cho các nhiệm vụ thường xuyên xảy ra

  • thuận tiện để sử dụng

  • và hiệu quả hơn về các yêu cầu thời gian và bộ nhớ CPU so với chỉ sử dụng chức năng Python mã.

Chúng tôi liệt kê ba mô -đun như vậy nói riêng: đặc biệt:

  • Mô-đun

    import scipy.integrate
    
    scipy.integrate?
    
    3 cung cấp một loại dữ liệu chuyên về số lượng vectơ và ma trận của các vectơ và ma trận (đây là loại
    import scipy.integrate
    
    scipy.integrate?
    
    4 được cung cấp bởi ____ ____33, như được giới thiệu trong 14-numpy.ipynb) và các công cụ đại số tuyến tính.

  • Gói

    import scipy.integrate
    
    scipy.integrate?
    
    6 (cũng được biết đến là
    import scipy.integrate
    
    scipy.integrate?
    
    7) cung cấp khả năng vẽ đồ thị và trực quan

  • Gói

    import scipy.integrate
    
    scipy.integrate?
    
    8 (Python khoa học) cung cấp vô số thuật toán số và được giới thiệu trong chương này.

Nhiều thuật toán số có sẵn thông qua

import scipy.integrate

scipy.integrate?
8 và
import scipy.integrate

scipy.integrate?
3 được cung cấp bởi các thư viện biên dịch được thiết lập thường được viết bằng Fortran hoặc C. Do đó, chúng sẽ thực hiện nhanh hơn nhiều so với mã Python thuần túy (được giải thích). Theo nguyên tắc thông thường, chúng tôi hy vọng mã được biên dịch sẽ nhanh hơn hai bậc so với mã Python thuần túy.

Bạn có thể sử dụng chức năng trợ giúp cho từng phương thức số để tìm hiểu thêm về nguồn thực hiện.

Scipy¶

=============================================
Integration and ODEs (:mod:`scipy.integrate`)
=============================================

.. currentmodule:: scipy.integrate

Integrating functions, given function object
============================================

.. autosummary::
   :toctree: generated/

   quad          -- General purpose integration
   dblquad       -- General purpose double integration
   tplquad       -- General purpose triple integration
   nquad         -- General purpose n-dimensional integration
   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
   quadrature    -- Integrate with given tolerance using Gaussian quadrature
   romberg       -- Integrate func using Romberg integration
   quad_explain  -- Print information for use of quad
   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
   IntegrationWarning -- Warning on issues during integration

Integrating functions, given fixed samples
==========================================

.. autosummary::
   :toctree: generated/

   trapz         -- Use trapezoidal rule to compute integral.
   cumtrapz      -- Use trapezoidal rule to cumulatively compute integral.
   simps         -- Use Simpson's rule to compute integral from samples.
   romb          -- Use Romberg Integration to compute integral from
                 -- (2**k + 1) evenly-spaced samples.

.. seealso::

   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
   quadrature roots and weights for other weighting factors and regions.

Integrators of ODE systems
==========================

.. autosummary::
   :toctree: generated/

   odeint        -- General integration of ordinary differential equations.
   ode           -- Integrate ODE using VODE and ZVODE routines.
   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
1 được xây dựng trên
import scipy.integrate

scipy.integrate?
3. Tất cả các chức năng từ
import scipy.integrate

scipy.integrate?
3 dường như cũng có sẵn trong
import scipy.integrate

scipy.integrate?
8. Ví dụ, thay vì

In [1]:

import numpy
x = numpy.arange(0, 10, 0.1)
y = numpy.sin(x)

In [2]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)

Đầu tiên chúng ta cần nhập

import scipy.integrate

scipy.integrate?
8:

Gói

import scipy.integrate

scipy.integrate?
8 cung cấp thông tin về cấu trúc của chính nó khi chúng tôi sử dụng lệnh trợ giúp:

Đầu ra rất dài, vì vậy chúng tôi chỉ hiển thị một phần của nó ở đây:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)

Nếu chúng tôi đang tìm kiếm một thuật toán để tích hợp một hàm, chúng tôi có thể khám phá gói

=============================================
Integration and ODEs (:mod:`scipy.integrate`)
=============================================

.. currentmodule:: scipy.integrate

Integrating functions, given function object
============================================

.. autosummary::
   :toctree: generated/

   quad          -- General purpose integration
   dblquad       -- General purpose double integration
   tplquad       -- General purpose triple integration
   nquad         -- General purpose n-dimensional integration
   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
   quadrature    -- Integrate with given tolerance using Gaussian quadrature
   romberg       -- Integrate func using Romberg integration
   quad_explain  -- Print information for use of quad
   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
   IntegrationWarning -- Warning on issues during integration

Integrating functions, given fixed samples
==========================================

.. autosummary::
   :toctree: generated/

   trapz         -- Use trapezoidal rule to compute integral.
   cumtrapz      -- Use trapezoidal rule to cumulatively compute integral.
   simps         -- Use Simpson's rule to compute integral from samples.
   romb          -- Use Romberg Integration to compute integral from
                 -- (2**k + 1) evenly-spaced samples.

.. seealso::

   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
   quadrature roots and weights for other weighting factors and regions.

Integrators of ODE systems
==========================

.. autosummary::
   :toctree: generated/

   odeint        -- General integration of ordinary differential equations.
   ode           -- Integrate ODE using VODE and ZVODE routines.
   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
7:

import scipy.integrate

scipy.integrate?

produces:

=============================================
Integration and ODEs (:mod:`scipy.integrate`)
=============================================

.. currentmodule:: scipy.integrate

Integrating functions, given function object
============================================

.. autosummary::
   :toctree: generated/

   quad          -- General purpose integration
   dblquad       -- General purpose double integration
   tplquad       -- General purpose triple integration
   nquad         -- General purpose n-dimensional integration
   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
   quadrature    -- Integrate with given tolerance using Gaussian quadrature
   romberg       -- Integrate func using Romberg integration
   quad_explain  -- Print information for use of quad
   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
   IntegrationWarning -- Warning on issues during integration

Integrating functions, given fixed samples
==========================================

.. autosummary::
   :toctree: generated/

   trapz         -- Use trapezoidal rule to compute integral.
   cumtrapz      -- Use trapezoidal rule to cumulatively compute integral.
   simps         -- Use Simpson's rule to compute integral from samples.
   romb          -- Use Romberg Integration to compute integral from
                 -- (2**k + 1) evenly-spaced samples.

.. seealso::

   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
   quadrature roots and weights for other weighting factors and regions.

Integrators of ODE systems
==========================

.. autosummary::
   :toctree: generated/

   odeint        -- General integration of ordinary differential equations.
   ode           -- Integrate ODE using VODE and ZVODE routines.
   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.

Các phần sau đây cho thấy các ví dụ chứng minh cách sử dụng các thuật toán được cung cấp bởi

import scipy.integrate

scipy.integrate?
8.

Hội nhập số¶

Python khoa học cung cấp một số thói quen tích hợp. Một công cụ mục đích chung để giải quyết các tích phân I thuộc loại

$$ i = \ int_a^b f (x) \ mathrm {d} x $$

được cung cấp bởi hàm

=============================================
Integration and ODEs (:mod:`scipy.integrate`)
=============================================

.. currentmodule:: scipy.integrate

Integrating functions, given function object
============================================

.. autosummary::
   :toctree: generated/

   quad          -- General purpose integration
   dblquad       -- General purpose double integration
   tplquad       -- General purpose triple integration
   nquad         -- General purpose n-dimensional integration
   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
   quadrature    -- Integrate with given tolerance using Gaussian quadrature
   romberg       -- Integrate func using Romberg integration
   quad_explain  -- Print information for use of quad
   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
   IntegrationWarning -- Warning on issues during integration

Integrating functions, given fixed samples
==========================================

.. autosummary::
   :toctree: generated/

   trapz         -- Use trapezoidal rule to compute integral.
   cumtrapz      -- Use trapezoidal rule to cumulatively compute integral.
   simps         -- Use Simpson's rule to compute integral from samples.
   romb          -- Use Romberg Integration to compute integral from
                 -- (2**k + 1) evenly-spaced samples.

.. seealso::

   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
   quadrature roots and weights for other weighting factors and regions.

Integrators of ODE systems
==========================

.. autosummary::
   :toctree: generated/

   odeint        -- General integration of ordinary differential equations.
   ode           -- Integrate ODE using VODE and ZVODE routines.
   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
9 của mô -đun
from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))
0.

Nó lấy các đối số đầu vào hàm f (x) để được tích hợp (tích phân trên mạng) và phần dưới và trên giới hạn a và b. Nó trả về hai giá trị (trong một tuple): giá trị đầu tiên là kết quả được tính toán và giá trị thứ hai là ước tính sai số số của kết quả đó.

Dưới đây là một ví dụ: tạo ra đầu ra này:

In [4]:

from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))

The numerical result is 17.864264 (+-1.55113e-11)

Lưu ý rằng

=============================================
Integration and ODEs (:mod:`scipy.integrate`)
=============================================

.. currentmodule:: scipy.integrate

Integrating functions, given function object
============================================

.. autosummary::
   :toctree: generated/

   quad          -- General purpose integration
   dblquad       -- General purpose double integration
   tplquad       -- General purpose triple integration
   nquad         -- General purpose n-dimensional integration
   fixed_quad    -- Integrate func(x) using Gaussian quadrature of order n
   quadrature    -- Integrate with given tolerance using Gaussian quadrature
   romberg       -- Integrate func using Romberg integration
   quad_explain  -- Print information for use of quad
   newton_cotes  -- Weights and error coefficient for Newton-Cotes integration
   IntegrationWarning -- Warning on issues during integration

Integrating functions, given fixed samples
==========================================

.. autosummary::
   :toctree: generated/

   trapz         -- Use trapezoidal rule to compute integral.
   cumtrapz      -- Use trapezoidal rule to cumulatively compute integral.
   simps         -- Use Simpson's rule to compute integral from samples.
   romb          -- Use Romberg Integration to compute integral from
                 -- (2**k + 1) evenly-spaced samples.

.. seealso::

   :mod:`scipy.special` for orthogonal polynomials (special) for Gaussian
   quadrature roots and weights for other weighting factors and regions.

Integrators of ODE systems
==========================

.. autosummary::
   :toctree: generated/

   odeint        -- General integration of ordinary differential equations.
   ode           -- Integrate ODE using VODE and ZVODE routines.
   complex_ode   -- Convert a complex-valued ODE to real-valued and integrate.
9 có các tham số tùy chọn
from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))
2 và
from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))
3 để tăng hoặc giảm độ chính xác của tính toán của nó. (Sử dụng
from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))
4 để tìm hiểu thêm.) Các giá trị mặc định là
from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))
5 và
from math import cos, exp, pi
from scipy.integrate import quad

# function we want to integrate
def f(x):
    return exp(cos(-2 * x * pi)) + 3.2

# call quad to integrate f from -2 to 2
res, err = quad(f, -2, 2)

print("The numerical result is {:f} (+-{:g})"
    .format(res, err))
6. Đối với bài tập tiếp theo, các giá trị mặc định là đủ.

Bài tập: Tích hợp một chức năng

  1. Sử dụng chức năng SCIPY từ

    from math import cos, exp, pi
    from scipy.integrate import quad
    
    # function we want to integrate
    def f(x):
        return exp(cos(-2 * x * pi)) + 3.2
    
    # call quad to integrate f from -2 to 2
    res, err = quad(f, -2, 2)
    
    print("The numerical result is {:f} (+-{:g})"
        .format(res, err))
    
    7, hãy viết một chương trình giải quyết tích phân sau: $ i = \ int _0^1 \ cos (2 \ pi x) dx $.

  2. Tìm tích phân phân tích và so sánh nó với giải pháp số.

  3. Tại sao điều quan trọng là phải có một ước tính về độ chính xác (hoặc lỗi) của tích phân số?

Tập thể dục: Cấu trúc trước khi bạn tích hợp công

Đó là một thực tiễn tốt để vẽ hình thức chức năng tích phân để kiểm tra xem đó có phải là hành vi tốt hay không trước khi bạn cố gắng tích hợp. Điểm kỳ lạ (tức là $ x $ các giá trị trong đó $ f (x) $ có xu hướng đối với trừ hoặc cộng vô cực) hoặc hành vi bất thường khác (chẳng hạn như $ f (x) = \ sin (\ frac {1} {x} $) $ x = 0 $ rất khó để xử lý bằng số.

  1. Viết một chức năng có tên
    from math import cos, exp, pi
    from scipy.integrate import quad
    
    # function we want to integrate
    def f(x):
        return exp(cos(-2 * x * pi)) + 3.2
    
    # call quad to integrate f from -2 to 2
    res, err = quad(f, -2, 2)
    
    print("The numerical result is {:f} (+-{:g})"
        .format(res, err))
    
    8 có các đối số giống như lệnh Quad (tức là $ f $, $ a $ và $ b $) và đó
  2. (i) Tạo một lô của Integrand $ f (x) $ và
  3. (ii) Tính toán tích phân bằng cách sử dụng hàm
    from math import cos, exp, pi
    from scipy.integrate import quad
    
    # function we want to integrate
    def f(x):
        return exp(cos(-2 * x * pi)) + 3.2
    
    # call quad to integrate f from -2 to 2
    res, err = quad(f, -2, 2)
    
    print("The numerical result is {:f} (+-{:g})"
        .format(res, err))
    
    7. Các giá trị trả về phải như đối với hàm
    from math import cos, exp, pi
    from scipy.integrate import quad
    
    # function we want to integrate
    def f(x):
        return exp(cos(-2 * x * pi)) + 3.2
    
    # call quad to integrate f from -2 to 2
    res, err = quad(f, -2, 2)
    
    print("The numerical result is {:f} (+-{:g})"
        .format(res, err))
    
    7.

Giải các phương trình vi phân thông thường

Để giải một phương trình vi phân thông thường của loại $$ \ frac {\ mathrm {d} y} {\ mathrm {d} t} (t) = f (y, t) $$ $$

Với một $ y đã cho (t_0) = y_0 $, chúng ta có thể sử dụng chức năng ____ 38 ____ ____62. Đây là một chương trình ví dụ (tự giải thích) (

The numerical result is 17.864264 (+-1.55113e-11)
3) để tìm

$$ y (t) \ Quad \ mathrm {for} \ Quad t \ in [0,2] $$

Cho phương trình vi phân này: $$ \ frac {\ mathrm {d} y} {\ mathrm {d} t} (t) = -2yt \ Quad \ mathrm {with} \ Quad y (0) = 1. $$

In [5]:

%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')

Out[5]:

<matplotlib.text.Text at 0x10cad9320>

Lệnh

The numerical result is 17.864264 (+-1.55113e-11)
2 cần một số tham số tùy chọn để thay đổi dung sai lỗi mặc định của tích hợp (và để kích hoạt sản xuất đầu ra gỡ lỗi thêm). Sử dụng lệnh trợ giúp để khám phá sau:

help(scipy.integrate.odeint)

sẽ hiển thị:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
0

Bài tập: Sử dụng ________ 62¶

  1. Mở một tệp mới với tệp

    The numerical result is 17.864264 (+-1.55113e-11)
    
    6 trong trình soạn thảo văn bản.

  2. Viết một chương trình tính toán giải pháp y (t) của ode này bằng thuật toán

    The numerical result is 17.864264 (+-1.55113e-11)
    
    2: $$ \ frac {\ mathrm {d} y} {\ mathrm {d} t} = -\ exp (-t) (10 \ sin (10t)+\ cos (10t)) $$ từ $ t = 0 $ đến $ t = 10 $. Giá trị ban đầu là $ y (0) = 1 $.

  3. Bạn nên hiển thị giải pháp bằng đồ họa tại các điểm $ t = 0 $, $ t = 0,01 $, $ t = 0,02 $, ..., $ t = 9,99 $, $ t = 10 $.

Gợi ý: Một phần của giải pháp $ y (t) $ được hiển thị trong hình dưới đây.

Hướng dẫn how do you write an integral code in python? - làm thế nào để bạn viết một mã tích phân trong python?

Phát hiện gốc

Nếu bạn cố gắng tìm một $ x $ sao cho $$ f (x) = 0 $$ thì đây được gọi là tìm kiếm gốc. Lưu ý rằng các vấn đề như $ g (x) = h (x) $ rơi vào danh mục này vì bạn có thể viết lại chúng là $ f (x) = g (x) H (x) = 0 $.

Một số công cụ tìm kiếm gốc có sẵn trong mô -đun ____ 38 ____ ____69.

Tìm kiếm gốc bằng phương pháp chia đôi

Đầu tiên chúng tôi giới thiệu thuật toán

%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')
0 là (i) mạnh mẽ và (ii) chậm nhưng về mặt khái niệm rất đơn giản.

Giả sử chúng ta cần tính toán rễ của f (x) = x3 - 2x2. Hàm này có gốc (đôi) tại x = 0 (điều này là tầm thường để xem) và một gốc khác nằm giữa x = 1,5 (trong đó f (1.5) = - 1.125) và x = 3 (trong đó f (3) = = 9). Thật là khá đơn giản khi thấy rằng gốc khác này được đặt tại x = 2. Đây là một chương trình xác định số gốc này:

In [6]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
1

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
2

Phương pháp

%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')
1 có ba đối số bắt buộc: (i) hàm f (x), (ii) giới hạn thấp hơn A (mà chúng tôi đã chọn 1.5 trong ví dụ của chúng tôi) và (ii) giới hạn trên B (mà chúng tôi đã chọn 3). Tham số tùy chọn
%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')
2 xác định lỗi tối đa của phương thức.

Một trong những yêu cầu của phương pháp chia đôi là khoảng [A, B] phải được chọn sao cho hàm này dương ở mức A và âm ở B hoặc hàm âm tính ở A và tư thế tại b. Nói cách khác: A và B phải đặt một gốc.

Bài tập: Tìm kiếm gốc bằng phương pháp Bisect

  1. Viết một chương trình có tên

    %matplotlib inline
    from scipy.integrate import odeint
    import numpy as N
    
    def f(y, t):
        """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
        return -2 * y * t
    
    y0 = 1             # initial value
    a = 0              # integration limits for t
    b = 2
    
    t = N.arange(a, b, 0.01)  # values of t for
                              # which we require
                              # the solution y(t)
    y = odeint(f, y0, t)  # actual computation of y(t)
    
    import pylab          # plotting of results
    pylab.plot(t, y)
    pylab.xlabel('t'); pylab.ylabel('y(t)')
    
    3 để xác định xấp xỉ $ \ sqrt {2} $ bằng cách tìm gốc x của hàm $ f (x) = 2 - x^2 $ bằng thuật toán chia đôi. Chọn dung sai cho xấp xỉ của gốc 10−8.

  2. Ghi lại sự lựa chọn của bạn về khung ban đầu $ [A, B] $ cho gốc: Bạn đã chọn giá trị nào cho A và cho B và tại sao?

  3. Nghiên cứu kết quả:

    • Giá trị nào cho thuật toán chia đôi gốc x?

    • Tính giá trị của $ \\ SQRT {2} $ bằng cách sử dụng

      %matplotlib inline
      from scipy.integrate import odeint
      import numpy as N
      
      def f(y, t):
          """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
          return -2 * y * t
      
      y0 = 1             # initial value
      a = 0              # integration limits for t
      b = 2
      
      t = N.arange(a, b, 0.01)  # values of t for
                                # which we require
                                # the solution y(t)
      y = odeint(f, y0, t)  # actual computation of y(t)
      
      import pylab          # plotting of results
      pylab.plot(t, y)
      pylab.xlabel('t'); pylab.ylabel('y(t)')
      
      4 và so sánh điều này với xấp xỉ của gốc. Làm thế nào lớn là lỗi tuyệt đối của x? Làm thế nào để so sánh với
      %matplotlib inline
      from scipy.integrate import odeint
      import numpy as N
      
      def f(y, t):
          """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
          return -2 * y * t
      
      y0 = 1             # initial value
      a = 0              # integration limits for t
      b = 2
      
      t = N.arange(a, b, 0.01)  # values of t for
                                # which we require
                                # the solution y(t)
      y = odeint(f, y0, t)  # actual computation of y(t)
      
      import pylab          # plotting of results
      pylab.plot(t, y)
      pylab.xlabel('t'); pylab.ylabel('y(t)')
      
      2?

Tìm kiếm gốc bằng cách sử dụng funcion ____76

A (thường) tốt hơn (theo nghĩa của thuật toán hiệu quả hơn) so với thuật toán chia đôi được thực hiện trong hàm

%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')
7 mục đích chung để tìm thấy các hàm (đa chiều). Thuật toán này chỉ cần một điểm bắt đầu gần vị trí nghi ngờ của gốc (nhưng không phải là garanteed để hội tụ).

Đây là một ví dụ:

In [7]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
3

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
4

Giá trị trả về [6] của

%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')
6 là một mảng độ dài n tăng cho một vấn đề tìm kiếm gốc với các biến n. Trong ví dụ trên, chúng ta có n = 1.

Nội suy

Đưa ra một bộ N điểm $ (x_i, y_i) $ với $ i = 1, 2, N N $, đôi khi chúng ta cần một hàm $ \ hat {f} (x) $ mà trả về $ y_i = f (x_i) $ trong đó $ x == x_i $, và ngoài ra còn cung cấp một số phép nội suy của dữ liệu $ (x_i, y_i) $ cho tất cả $ x $.

Hàm

%matplotlib inline
from scipy.integrate import odeint
import numpy as N

def f(y, t):
    """this is the rhs of the ODE to integrate, i.e. dy/dt=f(y,t)"""
    return -2 * y * t

y0 = 1             # initial value
a = 0              # integration limits for t
b = 2

t = N.arange(a, b, 0.01)  # values of t for
                          # which we require
                          # the solution y(t)
y = odeint(f, y0, t)  # actual computation of y(t)

import pylab          # plotting of results
pylab.plot(t, y)
pylab.xlabel('t'); pylab.ylabel('y(t)')
9 thực hiện phép nội suy này dựa trên các spline theo thứ tự khác nhau. Lưu ý rằng hàm
<matplotlib.text.Text at 0x10cad9320>
0 trả về hàm
<matplotlib.text.Text at 0x10cad9320>
1 sau đó sẽ nội suy dữ liệu X-Y cho bất kỳ $ x $ nào khi được gọi là $ y0 (x) $.

Mã dưới đây thể hiện điều này và hiển thị các loại nội suy khác nhau.

In [8]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
5

Out[8]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
6

Phù hợp với đường cong

Chúng ta đã thấy trong chương Numpy rằng chúng ta có thể phù hợp với các hàm đa thức thông qua một tập dữ liệu bằng hàm

<matplotlib.text.Text at 0x10cad9320>
2. Ở đây, chúng tôi giới thiệu một thuật toán phù hợp với đường cong chung hơn.

SCIPY cung cấp một hàm hơi chung chung (dựa trên thuật toán Levenburg-Marquest) thông qua

<matplotlib.text.Text at 0x10cad9320>
3 để phù hợp với hàm (python) nhất định cho một tập dữ liệu nhất định. Giả định là chúng tôi đã được cung cấp một bộ dữ liệu với các điểm $ x_1, x_2, trên X_N $ và với các giá trị chức năng tương ứng $ y_i $ và sự phụ thuộc của $ y_i $ trên $ x_i $ sao cho $ y_i = f (x_i, \ vec {p}) $. Chúng tôi muốn xác định vectơ tham số $ \ vec {p} = (p_1, p_2, \ ldots, p_k) $ để $ r $, tổng của phần dư, càng nhỏ càng tốt:

$$ r = \ sum \ limits_ {i = 1}^n \ left (y_i - f (x_i, \ vec {p}) \ right)^2 $$

Phù hợp với đường cong được sử dụng đặc biệt nếu dữ liệu ồn ào: với $ x_i $ và $ y_i = f (x_i, \ vec {p}) $ Chúng tôi có một thuật ngữ lỗi (chưa biết) $ \ epsilon_i $ để $ y_i = f (x_i, \ vec {p})+\ epsilon_i $.

Chúng tôi sử dụng ví dụ sau để làm rõ điều này: $$ f (x, \ vec {p}) = a \ exp (-b x) + c, \ Quad \ mathrm {i.e. A, B, C} $$

In [9]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
7

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
8

Out[9]:

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
9

Lưu ý rằng trong mã nguồn ở trên, chúng tôi xác định hàm phù hợp $ y = f (x) $ thông qua mã python. Do đó, chúng ta có thể phù hợp (gần) các hàm tùy ý bằng phương pháp

<matplotlib.text.Text at 0x10cad9320>
4.

Hàm

<matplotlib.text.Text at 0x10cad9320>
4 trả về một tuple
<matplotlib.text.Text at 0x10cad9320>
6. Mục đầu tiên
<matplotlib.text.Text at 0x10cad9320>
7 chứa một bộ của các tham số tối ưu (theo nghĩa là các phương trình giảm thiểu này ([eq: 1]). Mục thứ hai chứa ma trận hiệp phương sai cho tất cả các tham số. Các đường chéo cung cấp phương sai của ước tính tham số.

Đối với quy trình phù hợp với đường cong hoạt động, thuật toán Levenburg-Marquest cần bắt đầu quá trình phù hợp với các dự đoán ban đầu cho các tham số cuối cùng. Nếu chúng không được chỉ định (như trong ví dụ trên), giá trị 1.0 1.0 được sử dụng cho dự đoán ban đầu.

Nếu thuật toán không phù hợp với hàm cho dữ liệu (mặc dù hàm mô tả dữ liệu một cách hợp lý), chúng ta cần cung cấp cho thuật toán ước tính tốt hơn cho các tham số ban đầu. Đối với ví dụ được hiển thị ở trên, chúng tôi có thể đưa ra các ước tính cho hàm

<matplotlib.text.Text at 0x10cad9320>
4 bằng cách thay đổi dòng

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
0

đến

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
1

Nếu dự đoán ban đầu của chúng tôi sẽ là A = 2, B = 1 và C = 0,6. Khi chúng tôi lấy thuật toán, ở đúng khu vực, trong không gian tham số, việc phù hợp thường hoạt động tốt.

Fourier Transforms¶

Trong ví dụ tiếp theo, chúng tôi tạo ra một tín hiệu như một sự chồng chất của sóng hình sin 50 Hz và 70 Hz (với sự thay đổi pha nhỏ giữa chúng). Sau đó, Fourier biến đổi tín hiệu và biểu thị giá trị tuyệt đối của các hệ số biến đổi Fourier rời rạc (phức tạp) theo tần số và dự kiến ​​sẽ thấy các đỉnh ở 50Hz và 70Hz.

In [10]:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
2

Out[10]:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
3

Biểu đồ thấp hơn cho thấy biến đổi Fourier rời rạc được tính toán từ dữ liệu được hiển thị trong biểu đồ trên.

Tối ưu hóa¶

Thông thường chúng ta cần tìm mức tối đa hoặc tối thiểu của một hàm cụ thể f (x) trong đó f là hàm vô hướng nhưng x có thể là một vectơ. Các ứng dụng điển hình là việc giảm thiểu các thực thể như chi phí, rủi ro và lỗi hoặc tối đa hóa năng suất, hiệu quả và lợi nhuận. Các thói quen tối ưu hóa thường cung cấp một phương thức để giảm thiểu hàm đã cho: nếu chúng ta cần tối đa hóa f (x), chúng ta tạo một hàm mới g (x) đảo ngược dấu hiệu của f, tức là g (x) = - f (x) và chúng ta giảm thiểu g (x).

Dưới đây, chúng tôi cung cấp một ví dụ hiển thị (i) định nghĩa về hàm thử nghiệm và (ii) lệnh gọi của hàm

<matplotlib.text.Text at 0x10cad9320>
9 lấy hàm một hàm F để giảm thiểu và giá trị ban đầu X0 để bắt đầu tìm kiếm tối thiểu, và trả về giá trị của x mà f (x) được giảm thiểu (cục bộ). Thông thường, việc tìm kiếm tối thiểu là một tìm kiếm cục bộ, tức là thuật toán theo độ dốc cục bộ. Chúng tôi lặp lại tìm kiếm tối thiểu cho hai giá trị (x0 = 1.0 và x0 = 2.0, tương ứng) để chứng minh rằng tùy thuộc vào giá trị bắt đầu, chúng tôi có thể tìm thấy các tối thiểu khác nhau của hàm f.

Phần lớn các lệnh (sau hai cuộc gọi đến

help(scipy.integrate.odeint)
0) trong tệp
help(scipy.integrate.odeint)
1 tạo ra sơ đồ của hàm, các điểm bắt đầu cho các tìm kiếm và cực tiểu thu được:

In [11]:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
4

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
5

Out[11]:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
6

Gọi hàm

help(scipy.integrate.odeint)
0 sẽ tạo ra một số đầu ra chẩn đoán mà bạn cũng có thể thấy ở trên.

Giá trị trả lại của ________ 90¶

Lưu ý rằng giá trị trả về từ hàm

help(scipy.integrate.odeint)
0 là
import scipy.integrate

scipy.integrate?
4 numpy - đối với ví dụ trên - chỉ chứa một số vì chúng ta chỉ có một tham số (ở đây x) để thay đổi. Nói chung,
help(scipy.integrate.odeint)
0 có thể được sử dụng để tìm mức tối thiểu trong không gian tham số chiều cao hơn nếu có một số tham số. Trong trường hợp đó, mảng numpy sẽ chứa các tham số để giảm thiểu hàm mục tiêu. Hàm mục tiêu $ f (x) $ phải trả về vô hướng ngay cả khi có nhiều tham số hơn, tức là ngay cả khi $ x $ là một vectơ như trong $ f (\ mathbf {x}) $.

Các phương pháp số khác

Python và Numpy khoa học cung cấp quyền truy cập vào một số lượng lớn các thuật toán số khác bao gồm nội suy hàm, biến đổi Fourier, tối ưu hóa, các hàm đặc biệt (như hàm Bessel), xử lý tín hiệu và bộ lọc, tạo số ngẫu nhiên, v.v. Bắt đầu khám phá ________ 38 và ________ 33 Khả năng sử dụng chức năng

help(scipy.integrate.odeint)
9 và tài liệu được cung cấp trên web.

SCIPY.IO: đầu ra của Scipy-input

SCIPY cung cấp các thói quen để đọc và viết các tệp MATLAB

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
00. Dưới đây là một ví dụ trong đó chúng tôi tạo một tệp tương thích MATLAB lưu trữ ma trận (1x11) và sau đó đọc dữ liệu này thành một mảng không có từ Python bằng thư viện đầu vào đầu vào Scipy:

Trước tiên, chúng tôi tạo một tệp mat trong quãng tám (octave [chủ yếu] tương thích với MATLAB):

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
7

Sau đó, chúng tôi tải mảng này trong Python:

In [12]:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
8

Out[13]:

stats       --- Statistical Functions [*]
sparse      --- Sparse matrix [*]
lib         --- Python wrappers to external libraries [*]
linalg      --- Linear algebra routines [*]
signal      --- Signal Processing Tools [*]
misc        --- Various utilities that don't have another home.
interpolate --- Interpolation Tools [*]
optimize    --- Optimization Tools [*]
cluster     --- Vector Quantization / Kmeans [*]
fftpack     --- Discrete Fourier Transform algorithms [*]
io          --- Data input and output [*]
integrate   --- Integration routines [*]
lib.lapack  --- Wrappers to LAPACK library [*]
special     --- Special Functions [*]
lib.blas    --- Wrappers to BLAS library [*]
  [*] - using a package requires explicit import (see pkgload)
9

Out[14]:

import scipy.integrate

scipy.integrate?
0

Hàm

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
01 Trả về từ điển: Khóa cho mỗi mục trong từ điển là một chuỗi là tên của mảng đó khi nó được lưu trong MATLAB. Chìa khóa là mảng thực tế.

Một tệp ma trận MATLAB có thể chứa một số mảng. Mỗi trong số đó được trình bày bởi một cặp giá trị khóa trong từ điển.

Hãy để lưu hai mảng từ Python để chứng minh rằng:

In [15]:

import scipy.integrate

scipy.integrate?
1

Chương trình này tạo ra tệp

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
02, mà sau đó chúng ta có thể đọc bằng MATLAB hoặc ở đây Octave:

import scipy.integrate

scipy.integrate?
2

Lưu ý rằng có các chức năng khác để đọc và ghi vào các định dạng như được sử dụng bởi IDL, NETCDF và các định dạng khác trong

import scipy as s
x = s.arange(0, 10, 0.1)
y = s.sin(x)
03.

Thêm → Xem Hướng dẫn SCIPY.

Có một chức năng tích hợp trong Python?

Mô -đun tích hợp số.Nó lấy các đối số đầu vào hàm f (x) để được tích hợp (tích phân trên mạng) và phần dưới và trên giới hạn a và b.Nó trả về hai giá trị (trong một tuple): giá trị đầu tiên là kết quả được tính toán và giá trị thứ hai là ước tính sai số số của kết quả đó. integrate module. It takes as input arguments the function f(x) to be integrated (the “integrand”), and the lower and upper limits a and b. It returns two values (in a tuple): the first one is the computed results and the second one is an estimation of the numerical error of that result.

Numpy có thể tích hợp không?

Trapz.Tích hợp dọc theo trục đã cho bằng cách sử dụng quy tắc hình thang tổng hợp.Nếu X được cung cấp, sự tích hợp xảy ra theo trình tự dọc theo các yếu tố của nó - chúng không được sắp xếp.. Integrate along the given axis using the composite trapezoidal rule. If x is provided, the integration happens in sequence along its elements - they are not sorted.