user8788942
user8788942

Reputation:

error in my simpsons rule integration

I have written the following code to use simpson's rule to integrate an arbitrary function, in my case, sin(x):

import math


delta_x=(x2-x1)/N

def simpson(x1,x2,f,N):
    sum=0
    i=1
    for i in range(1,N+1):

        sum+=f(x1+i*delta_x)

    sum1=(3*delta_x)*sum

    return(sum1)

print(simpson(0,math.pi,math.sin(x),100))

however I get the error 'float object not callable' on the sum+=f(x1+i*delta_x) line. Anyone know what could be wrong?

Thanks :)

Upvotes: 0

Views: 300

Answers (1)

Barmar
Barmar

Reputation: 782785

The f argument to your function is supposed to be a function. math.sin(x) doesn't return a function, it calculates the sin of x and returns that number. simpson() is then trying to call it as a function.

You should just pass math.sin, it will be called by simpson() in the loop.

print(simpson(0,math.pi,math.sin,100))

Upvotes: 1

Related Questions