Формула трех восьмых питон

scipy.integrate.simpson#

Integrate y(x) using samples along the given axis and the composite Simpson’s rule. If x is None, spacing of dx is assumed.

If there are an even number of samples, N, then there are an odd number of intervals (N-1), but Simpson’s rule requires an even number of intervals. The parameter ‘even’ controls how this is handled.

Parameters : y array_like

x array_like, optional

If given, the points at which y is sampled.

dx float, optional

Spacing of integration points along axis of x. Only used when x is None. Default is 1.

axis int, optional

Axis along which to integrate. Default is the last axis.

  1. use the first N-2 intervals with a trapezoidal rule on the last interval and
  2. use the last N-2 intervals with a trapezoidal rule on the first interval.

a trapezoidal rule on the last interval.

‘last’ Use Simpson’s rule for the last N-2 intervals with a

trapezoidal rule on the first interval.

None : equivalent to ‘simpson’ (default)

‘simpson’ Use Simpson’s rule for the first N-2 intervals with the

addition of a 3-point parabolic segment for the last interval using equations outlined by Cartwright [1]. If the axis to be integrated over only has two points then the integration falls back to a trapezoidal integration.

Changed in version 1.11.0: The newly added ‘simpson’ option is now the default as it is more accurate in most situations.

Deprecated since version 1.11.0: Parameter even is deprecated and will be removed in SciPy 1.13.0. After this time the behaviour for an even number of points will follow that of even=’simpson’.

The estimated integral computed with the composite Simpson’s rule.

adaptive quadrature using QUADPACK

adaptive Romberg quadrature

adaptive Gaussian quadrature

fixed-order Gaussian quadrature

integrators for sampled data

cumulative integration for sampled data

For an odd number of samples that are equally spaced the result 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 only if the function is a polynomial of order 2 or less.

Cartwright, Kenneth V. Simpson’s Rule Cumulative Integration with MS Excel and Irregularly-spaced Data. Journal of Mathematical Sciences and Mathematics Education. 12 (2): 1-9

>>> from scipy import integrate >>> import numpy as np >>> x = np.arange(0, 10) >>> y = np.arange(0, 10) 
>>> y = np.power(x, 3) >>> integrate.simpson(y, x) 1640.5 >>> integrate.quad(lambda x: x**3, 0, 9)[0] 1640.25 
>>> integrate.simpson(y, x, even='first') 1644.5 

Источник

Читайте также:  Merge two sorted lists java

Simpson’s 3/8 Method Python Program

In this python program, lower_limit and upper_limit are lower and upper limit of integration, sub_interval is number of sub interval used while finding sum and function f(x) to be integrated by Simpson 3/8 method is defined using python function definition def f(x): .

Python Source Code: Simpson’s 3/8 Rule

 # Simpson's 3/8 Rule # Define function to integrate def f(x): return 1/(1 + x**2) # Implementing Simpson's 3/8 def simpson38(x0,xn,n): # calculating step size h = (xn - x0) / n # Finding sum integration = f(x0) + f(xn) for i in range(1,n): k = x0 + i*h if i%3 == 0: integration = integration + 2 * f(k) else: integration = integration + 3 * f(k) # Finding final integration value integration = integration * 3 * h / 8 return integration # Input section lower_limit = float(input("Enter lower limit of integration: ")) upper_limit = float(input("Enter upper limit of integration: ")) sub_interval = int(input("Enter number of sub intervals: ")) # Call trapezoidal() method and get result result = simpson38(lower_limit, upper_limit, sub_interval) print("Integration result by Simpson's 3/8 method is: %0.6f" % (result) ) 

Output

Enter lower limit of integration: 0 Enter upper limit of integration: 1 Enter number of sub intervals: 6 Integration result by Simpson's 3/8 method is: 0.735877
  • Algorithm for Bisection Method
  • Pseudocode for Bisection Method
  • C Program for Bisection Method
  • C++ Program for Bisection Method
  • MATLAB Program for Bisection Method
  • Python Program for Bisection Method
  • Bisection Method Advantages
  • Bisection Method Disadvantages
  • Bisection Method Features
  • Convergence of Bisection Method
  • Bisection Method Online Calculator

Источник

Метод Симпсона для вычисления интегралов на Python

Метод Симпсона – это численный метод вычисления определенных интегралов от функций, которые могут быть приближены квадратичным полиномом.

Интеграл можно представить в виде площади под кривой функции на определенном интервале, которую можно разбить на маленькие прямоугольники. Метод Симпсона основан на том, что площадь под кривой можно приблизить площадью параболы, которая проходит через три точки: начальную, конечную и среднюю точку.

Алгоритм метода Симпсона

Алгоритм вычисления интеграла с помощью метода Симпсона можно описать следующим образом:

  1. Задать начальную и конечную точки интервала интегрирования a и b, интегрируемую функцию f(x) и число разбиений n.
  2. Вычислить шаг интегрирования h = (b – a) / n.
  3. Вычислить значения f(x) в точках x_i = a + i * h для i = 0, 1, …, n.
  4. Вычислить значения площадей под параболами, проходящими через три соседние точки на каждом шаге, используя формулу метода Симпсона: S_i = (h / 3) * (f(x_i-1) + 4f(x_i) + f(x_i+1)) для i = 1, 3, 5, …, n-1.Заметим, что в формуле используются только нечётные i-е шаги.
  5. Суммировать полученные значения площадей, чтобы получить приближенное значение интеграла: I = S_1 + S_3 + … + S_n-1.
  6. Полученный результат можно уточнить, используя формулу Рунге: I2 = I + (I – I1) / 15,где I1 – значение интеграла, полученное с помощью метода Симпсона для n/2 шагов интегрирования.
  7. Повторять шаги 2-6 с более мелким шагом интегрирования, пока не будет достигнута нужная точность.
Читайте также:  Python include all files in directory

Вычисление методом Симпсона на Python по шагам

  • Объявляем функцию, которая и будет вычислять определённый интеграл методом Симпсона. Она принимает функцию f , нижний и верхний пределы a и b , и количество интервалов n .
def simpson_integration(f, a, b, n):
sum_1 = sum(f(a + i*h) for i in range(1, n, 2)) sum_2 = sum(f(a + i*h) for i in range(2, n, 2))
integral = (1/3) * h * (f(a) + 4*sum_1 + 2*sum_2 + f(b)) return integral

Полный код метода Симпсона на Python

def simpson_integration(f, a, b, n): """ Принимает функцию f, нижний и верхний пределы a и b, и количество интервалов n. Возвращает приближенное значение определенного интеграла функции f на интервале [a, b] методом Симпсона. """ # Вычисляем шаг интервала h = (b - a) / n # Считаем сумму значений функции в точках x_i = a + i*h для i = 0, 1, . n sum_1 = sum(f(a + i*h) for i in range(1, n, 2)) # Сумма значений в нечётных точках sum_2 = sum(f(a + i*h) for i in range(2, n, 2)) # Сумма значений в чётных точках # Вычисляем приближенное значение интеграла методом Симпсона integral = (1/3) * h * (f(a) + 4*sum_1 + 2*sum_2 + f(b)) return integral def f(x): return x # Функция, которую мы будем интегрировать a = 0.5 # Нижний предел интегрирования b = 1 # Верхний предел интегрирования n = 5 # Количество интервалов integral = simpson_integration(f, a, b, n) print("Приближенное значение интеграла:", integral)

Результат выполнения программы в консоли:

метод симпсона на пайтон, результат в консоли

Погрешность метода Симпсона

Погрешность метода Симпсона зависит от второй производной интегрируемой функции на заданном интервале. Если вторая производная функции достаточно мала, то метод Симпсона дает точный результат. Однако, если вторая производная функции слишком большая, то погрешность метода Симпсона может быть значительной. Это может произойти, например, если функция имеет узкий и высокий пик на заданном интервале.

Другие методы для вычисления интегралов, которые могут быть более удобны, чем метод Симпсона: метод трапеций, метод прямоугольников и метод Гаусса.

Источник

Simpson’s Rule

Simpson’s rule uses a quadratic polynomial on each subinterval of a partition to approximate the function $f(x)$ and to compute the definite integral. This is an improvement over the trapezoid rule which approximates $f(x)$ by a straight line on each subinterval of a partition.

The formula for Simpson’s rule is

where $N$ is an even number of subintervals of $[a,b]$, $\Delta x = (b — a)/N$ and $x_i = a + i \Delta x$.

Error Formula

We have seen that the error in a Riemann sum is inversely proportional to the size of the partition $N$ and the trapezoid rule is inversely proportional to $N^2$. The error formula in the theorem below shows that Simpson’s rule is even better as the error is inversely proportional to $N^4$.

Читайте также:  Ts2307 cannot find module css or its corresponding type declarations

Theorem Let $S_N(f)$ denote Simpson’s rule

where $N$ is an even number of subintervals of $[a,b]$, $\Delta x = (b — a)/N$ and $x_i = a + i \Delta x$. The error bound is

$$ E_N^S(f) = \left| \ \int_a^b f(x) \, dx — S_N(f) \ \right| \leq \frac K_4 $$

where $\left| \ f^(x) \ \right| \leq K_4$ for all $x \in [a,b]$.

Implementation

Let’s write a function called simps which takes input parameters $f$, $a$, $b$ and $N$ and returns the approximation $S_N(f)$. Furthermore, let’s assign a default value $N=50$.

def simps(f,a,b,N=50): '''Approximate the integral of f(x) from a to b by Simpson's rule. Simpson's rule approximates the integral \int_a^b f(x) dx by the sum: (dx/3) \sum_^ (f(x_ + 4f(x_) + f(x_)) where x_i = a + i*dx and dx = (b - a)/N. Parameters ---------- f : function Vectorized function of a single variable a , b : numbers Interval of integration [a,b] N : (even) integer Number of subintervals of [a,b] Returns ------- float Approximation of the integral of f(x) from a to b using Simpson's rule with N subintervals of equal length. Examples -------- >>> simps(lambda x : 3*x**2,0,1,10) 1.0 ''' if N % 2 == 1: raise ValueError("N must be an even integer.") dx = (b-a)/N x = np.linspace(a,b,N+1) y = f(x) S = dx/3 * np.sum(y[0:-1:2] + 4*y[1::2] + y[2::2]) return S 

Let’s test our function on integrals for which we know the exact value. For example, we know

Test our function again with the integral

scipy.integrate.simps

The SciPy subpackage scipy.integrate contains several functions for approximating definite integrals and numerically solving differential equations. Let’s import the subpackage under the name spi .

import scipy.integrate as spi 

The function scipy.integrate.simps computes the approximation of a definite integral by Simpson’s rule. Consulting the documentation, we see that all we need to do it supply arrays of $x$ and $y$ values for the integrand and scipy.integrate.simps returns the approximation of the integral using Simpson’s rule.

Examples

Approximate ln(2)

Find a value $N$ which guarantees that Simpson’s rule approximation $S_N(f)$ of the integral

satisfies $E_N^S(f) \leq 0.0001$.

therefore $\left| \, f^(x) \, \right| \leq 24$ for all $x \in [1,2]$ and so

$$ \frac 24 \leq 0.0001 \ \Rightarrow \ \frac \leq 1 \ \Rightarrow \ \left( \frac \right)^ \leq N $$

Compute Simpson’s rule with $N=8$ (the smallest even integer greater than 6.04)

approximation = simps(lambda x : 1/x,1,2,8) print(approximation) 

We could also use the function scipy.integrate.simps to compute the exact same result

N = 8; a = 1; b = 2; x = np.linspace(a,b,N+1) y = 1/x approximation = spi.simps(y,x) print(approximation) 

Verify that $E_N^S(f) \leq 0.0001$

np.abs(np.log(2) - approximation)  

Источник

Оцените статью