Simpson rule

The trapezoidal rule uses straight-line segments for approximations, but we can use curves instead. Simpson』s rule fits intervals with quadratic curves.

We require three points to specify a quadratic (not just two, as with a line). So the fit is of a quadratic to pairs of adjacent slices. Again, suppose the integrand is f(x), and the spacing is h. Suppose the three points are at ?h, 0,+h. Then fitting a quadratic Ax2 + Bx + C through these points gives

f(?h) = Ah^2 ? Bh + C f(0) = C f(h) = Ah^2 + Bh + C =) A =1/h^2[1/2*f(?h) ? f(0) +1/2*f(h)] B =1/2h[f(h) ? f(?h)]  C = f(0)

and the area under the curve from ?h to h is approximated by the area under the quadratic, so

begin{align} int_{?h}^{h}(Ax^2 + Bx + C)dx &=2/3Ah^3 + 2Ch &=1/3h[f(?h) + 4f(0) + f(h)] end{align}

which is Simpson』s rule. It approximates the area under two adjacent slices. You need to have an even number of slices for this to work consistently, and the approximate value of the integral comes out to

I(a, b) ≈1/3*h[f(a) + f(b) + 4 sum_{k odd 1,...,N?1} f(a + kh) + 2sum_{k, even, 2,...,N-2}f(a + kh)]

The two sums are calculatedseparately, using range(1,N, 2) and range(2,N, 2) for their summation conditions.

code:

from __future__ import division # Python 2 compatibilitynndef simpson(f, a, b, n):n """Approximates the definite integral of f from a to b by then composite Simpsons rule, using n subintervals (with n even)"""nn if n % 2:n raise ValueError("n must be even (received n=%d)" % n)nn h = (b - a) / nn s = f(a) + f(b)nn for i in range(1, n, 2):n s += 4 * f(a + i * h)n for i in range(2, n-1, 2):n s += 2 * f(a + i * h)nn return s * h / 3nn# Demonstrate that the method is exact for polynomials up to 3rd ordernprint(simpson(lambda x:x**3, 0.0, 10.0, 2)) # 2500.0nprint(simpson(lambda x:x**3, 0.0, 10.0, 100000)) # 2500.0nnprint(simpson(lambda x:x**4, 0.0, 10.0, 2)) # 20833.3333333nprint(simpson(lambda x:x**4, 0.0, 10.0, 100000)) # 20000.0n

推薦閱讀:

Kivy中文編程指南:圖形
【翻譯搬運】SciPy-Python科學演算法庫
Google Brain開源新的Python 庫:Tangent
OpenCV:圖片操作基本知識(二)

TAG:科学计算 | Python | 数值计算 |