如何在Python中使用Simpsons Rule进行集成?

时间:2016-04-17 16:17:35

标签: python physics

我正在尝试整合此功能:$regexPatternGallery= '{gallery}([^"]*){/gallery}'; preg_match($regexPatternGallery, $fulltext, $matchesGallery); if (!empty($matchesGallery[1])) { echo ('<p>matchesGallery: '.$matchesGallery[1].'</p>'); } 从0到2

我写了这个程序:

x^4 - 2x + 1

但我收到了这个错误:

def f(x):
    return (x**4)-(2*x)+1

N=10 
a=0.0
b=2.0
h=(b-a)/N

s=f(a)+f(b)

for k in range(1,N/2):
    s+=4*f(a+(2*k-1)*h)

for k in range(1,N/(2-1)):
    s1 +=f(a+(2*k*h)

M=(s)+(2*s1)
print((1/3.0)*h)*(3)

我尝试用不同的形式编写它,但我总是在File "<ipython-input-29-6107592420b6>", line 17 M=(s)+(2*s1): ^ SyntaxError: invalid syntax

中出错

3 个答案:

答案 0 :(得分:4)

您忘记了第二个for循环中的右括号:s1 += f(a+(2*k*h)。它应该是:

s1 += f(a + (2 * k * h)) # <<< here it is

答案 1 :(得分:2)

为了将来参考,您可能还会考虑使用scipy.integrate。 根据数据集的性质和分辨率,在这里查看 for some methods可能具有更高的准确度。

代码可能如下所示:

import scipy.integrate as int
x = [ ii/10. for ii in range(21)]
y = [ xi**4 - 2*xi + 1 for xi in x]
tahdah = int.simps(y,x,even='avg')
print(tahdah)

您可以使用铅笔和纸张确认4.4的结果和答案。

答案 2 :(得分:1)

您是否在维基百科上看过code example辛普森一家规则(以python编写)?为了未来的读者的利益,我会在此重新发布。

#!/usr/bin/env python3
from __future__ import division  # Python 2 compatibility

def simpson(f, a, b, n):
    """Approximates the definite integral of f from a to b by the
    composite Simpson's rule, using n subintervals (with n even)"""

    if n % 2:
        raise ValueError("n must be even (received n=%d)" % n)

    h = (b - a) / n
    s = f(a) + f(b)

    for i in range(1, n, 2):
        s += 4 * f(a + i * h)
    for i in range(2, n-1, 2):
        s += 2 * f(a + i * h)

    return s * h / 3

# Demonstrate that the method is exact for polynomials up to 3rd order
print(simpson(lambda x:x**3, 0.0, 10.0, 2))       # 2500.0
print(simpson(lambda x:x**3, 0.0, 10.0, 100000))  # 2500.0

print(simpson(lambda x:x**4, 0.0, 10.0, 2))       # 20833.3333333
print(simpson(lambda x:x**4, 0.0, 10.0, 100000))  # 20000.0