【问题标题】:How to Integrate Using Simpsons Rule in Python?如何在 Python 中使用辛普森规则进行集成?
【发布时间】:2016-07-29 20:47:39
【问题描述】:

我正在尝试集成这个功能:x^4 - 2x + 1 from 0 to 2

我写了这个程序:

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

我尝试以不同的形式编写它,但我总是在M 中收到错误

【问题讨论】:

  • 顺便说一句,您的辛普森规则公式不太正确。我在这里的旧答案可能会有所帮助stackoverflow.com/a/33715116/4014959
  • 您可能需要在循环中使用 s1=0 之前声明它。或使用s += 2*f(...)。

标签: python physics


【解决方案1】:

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

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

【讨论】:

  • 只是补充一下 - 通常,当您收到无效的语法错误时,通常上面的那一行就是问题所在。
【解决方案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 的答案。

【讨论】:

    【解决方案3】:

    你看过维基百科上辛普森规则的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 
    

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 2014-12-17
      相关资源
      最近更新 更多