pythonpython-3.xloopsnumerical-methodssimpsons-rule

Simpson's Rule using for loops (numerical integration)


I am trying to code Simpson's Rule in python using for loops and I keep getting an assertion error and cant find out why.

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)

sample:

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

Solution

  • Here's a fixed version of your code:

    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)
    

    Notes: