fosho
fosho

Reputation: 1676

Simpson's Rule returning 0

I coded a function for Simpson's Rule of numerical integration. For values of n more than or equal to 34, the function returns 0.

Here, n is the number of intervals, a is the start point, and b is the end point.

import math

def simpsons(f, a,b,n):
    x = []
    h = (b-a)/n
    for i in range(n+1):
        x.append(a+i*h)

    I=0
    for i in range(1,(n/2)+1):

        I+=f(x[2*i-2])+4*f(x[2*i-1])+f(x[2*i])
    return I*(h/3)

def func(x):
    return (x**(3/2))/(math.cosh(x))



x = []
print(simpsons(func,0,100,34))

I am not sure why this is happening. I also coded a function for the Trapezoidal Method and that does not return 0 even when n = 50. What is going on here?

Upvotes: 0

Views: 449

Answers (1)

Spell
Spell

Reputation: 384

Wikipedia has the code for Simpson's rule in Python :

from __future__ import division  # Python 2 compatibility
import math

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

def func(x):
    return (x**(3/2))/(math.cosh(x))

Upvotes: 1

Related Questions