Reputation: 37
I am just testing my hands in Python with the midpoint Riemann sum but I seem to be missing a step as my answer was wrong. Here is a sample of my code:
from math import pi, sin
a=0
b=pi/2
n=10
dx=(b-a)/n
ends = [a+i*dx for i in range(n+1)]
mids=[(i+i-1)/2 for i in ends]
f = lambda x: x*sin(x)
area = [f(i)*dx for i in mids]
sum(area)
My answer should be 1 but I got 0.5022. I suspect my comprehension list under mids is wrong but can't figure out how to fix it. Any help will be well appreciated.
Upvotes: 0
Views: 254
Reputation: 3385
For starters, you're taking 11 segments, not 10, because of range(n+1)
Then your calculation is wrong.
ends[0] == 0 (a == 0, i == 0 => a+i*dx == 0)
=> mids[0] == -1/2 (i == ends[0] => (i+i-1)/2 == -1/2)
If you use range(1, n+1)
instead, you get:
ends[0] == pi/20 (a == 0, i == 1 => a+i*dx == pi/20)
=> mids[0] == pi/20-1/2 (i == ends[0] == pi/20 => (i+i-1)/2 == (pi/10-1)/2)
These are still incorrect - ends
looks OK, but mids[0]
needs to evaluate to pi/40
My suggestion is to use a debugger to check the values at each point here and confirm they are what you think they should be.
Upvotes: 0
Reputation: 5156
mids
should be
mids = [(ends[i] + ends[i-1]) / 2 for i in range(1, len(ends))]
i-1
is not the i-1
th element of ends
. It is just the i
th element minus 1.
Upvotes: 2