1

我正在尝试使用 for 循环在 python 中编写辛普森规则,但我不断收到断言错误并且无法找出原因。

def integrate_numeric(xmin, xmax, N):
    xsum = 0
    msum = 0
    h = (xmax-xmin)//N

    for i in range(0, N):
        xsum += f(xmin + i*h)
        print (xsum)

    for i in range(0,N-1):
        msum += f(xmin + (h/2) + i*h)    
        print (msum)

    I = (h/6) * (f(xmin) + 4*(msum) + 2*(xsum) + f(xmax))
    return I

F:

def f(x):
    return (x**2) * numpy.sin(x)

样本:

assert numpy.isclose(integrate_numeric(xmin=0, xmax=4, N=50), 1.096591)
4

1 回答 1

2

这是您的代码的固定版本:

import numpy

def integrate_numeric(xmin, xmax, N):
    '''                                                                                                                               
    Numerical integral of f from xmin to xmax using Simpson's rule with                                                               
        N panels.                                                                                                                     
    '''
    xsum = 0
    msum = 0
    h = (xmax-xmin)/N

    for i in range(1, N):
        xsum += f(xmin + i*h)
        print(xsum)

    for i in range(0, N):
        msum += f(xmin + (h/2) + i*h)
        print(msum)

    I = (h/6) * (f(xmin) + 4*msum + 2*xsum + f(xmax))
    return I


def f(x):
    '''Function equivalent to x^2 sin(x).'''
    return (x**2) * numpy.sin(x)


assert numpy.isclose(integrate_numeric(xmin=0, xmax=4, N=50), 1.096591)

笔记:

  • 两个for循环中的范围已更改:我们希望第一个for循环以(so总值) 为步长,第二个 for 循环以xmin + h(xmin + (N-1)*h总值)为步长。hN-1xmin + h/2xmin + (N-1)*h + h/2hN
  • f在最终计算中,不需要应用msumand xsum:这些值已经是值的总和f。我们仍然需要评估的唯一地方fxminxmax。(注意:这已经在对问题的编辑中得到修复。)
  • 该行h = (xmax-xmin)//N必须是h = (xmax-xmin)/N. 您只需要这里的常规分区,而不是地板分区。这可能是您最初得到零的原因:h本来是0.
于 2019-10-27T20:13:52.703 回答