Reputation: 41
def trapezoidal(f, a, b, n):
h = float(b - a) / n
s = 0.0
s = s + f(a)
i=1
while i<=n-1:
s = s + f(a + i*h)
i= i +1
s = s + f(b)
s = s*h
return s
def f(x):
x = float(x)
return (-1/6)*(x-1)*(x-2)*(x+2)*(x-4)
lel = trapezoidal(f, -2, 4, 10)
print ("%.3f" % lel)
ok = f(-0.8)
print ok
I am trying to build a program that calculates integrals using the trapezoid rule. When I do it on paper it works fine but my f function does not work properly. For example f(-0.8) should be equal to 4.8384 but when I run it shows 29.0304. Please help?
Upvotes: 0
Views: 122
Reputation: 117981
If you are using Python 2.x
def f(x):
x = float(x)
return (-1/6)*(x-1)*(x-2)*(x+2)*(x-4)
The first term in your expression is doing integer division. The result of that division will be promoted to float
later during the multiplication, but it is too late by then.
>>> (-1/6)
-1
You need to keep everything in floats
def f(x):
x = float(x)
return (-1.0/6.0)*(x-1)*(x-2)*(x+2)*(x-4)
Upvotes: 3