1

In the following code I have implemented composite Simpson's rule. However I should be getting approximately $291$ but for some reason I am getting something different. I implemented a few other methods to test it and the proper answer was $291$ So how do I fix my code?

from math import pi,cos,sin
def SimpsonMethod(f,a,b,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+h*h)
    return s*h/3
 print(SimpsonMethod(lambda x: x**2,5,10,100))

giving the output

237.39917687499988
Bernard
  • 175,478
fr14
  • 717
  • 3
  • 10
  • 23

1 Answers1

1

Typo in the part of the function that calculates the even nodes, should be s+=2*f(a+i*h), this is after fixing:

from math import pi,cos,sin
def SimpsonMethod(f,a,b,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.
print(SimpsonMethod(lambda x: x**2,5,10,100))

and the result

291.66666666666674
caverac
  • 19,345