Reputation: 82
I made a function in Python which calculates a definite integral according to the Trapezoidal rule: Trapezoidal rule formula
That's the code:
from math import ceil
def Trapez_rule(f, a, b, n):
'''Calculates an estimation of a definite integral of a function f(x), between the boundries a, b, by dividing the area to n equal areas'''
sum = (f(a) + f(b)) / 2
for i in range(ceil((b * n))):
sum += f(a + i / n)
sum *= (b - a) / n
return sum
The answer it gives is 10 times higher that it should have returned. I can't find the source of the problem.
Upvotes: 0
Views: 321
Reputation: 2526
Assume:
a=10
b=20
n=5
These lines are the problem:
for i in range(ceil((b * n))):
sum += f(a + i / n)
i
go from 0 to 99
when i = 99 then:
f(a + i / n) => f(10 + 99/5) => f(29)
You use n false look at the post solution below, so this should work:
def Trapez_rule(f, a, b, n): h = (b-a) / float(n) sum = (f(a) + f(b)) / 2.w for i in range(1,n-1): sum += f(a + i * h) sum *= h return sum
Upvotes: 1
Reputation:
I went ahead and fixed your code, and also renamed the function to fit with the official style guide PEP-8.
def trapezium_rule_integral(f, a, b, n):
'''Calculates an estimate of the definite integral of a function f, between
the boundaries a and b, by dividing the area to n equal areas'''
height = (b - a) / n
x = a
ys = []
while x <= b:
ys.append(f(x))
x += height
estimate = 0.5 * height * ( (ys[0] + ys[-1]) + 2 * (sum(ys[1:-1])) )
return estimate
Upvotes: 0