How to find the left riemann sum using a for loop?
74 views (last 30 days)
Show older comments
I need to find the left sum of a function handle f, on the interval [a,b] with n subintervals. So far what I have is:
function r=myleftsum(f,a,b,n)
r=0;
dx=(b-a)/n;
for k=1:n
c=a+k*dx;
r=r+f(c);
end
r=dx*r;
end
I think this is taking the right sum but I need the left sum. I am not sure which line to change or what will make this code take the left sum.
0 Comments
Accepted Answer
Geoff Hayes
on 13 Aug 2014
Renee - since you are calculating the Left Riemann Sum, then the code needs to use the left-end point of each sub-interval. The left-end points are a,a+dx,a+2dx,...,a+(n-1)dx. So your code becomes
function r=myleftsum(f,a,b,n)
dx=(b-a)/n;
% initialize r to f(a) (the left-end point of the first sub-interval
% [a,a+dx])
r=f(a);
% need only consider the n-1 remaining sub-intervals
for k=1:n-1
c=a+k*dx;
r=r+f(c);
end
r=dx*r;
end
Try the above and see what happens!
2 Comments
Geoff Hayes
on 22 Jan 2020
Yes, I guess we could start from k=0 but then we'd need to initialize r to be zero instead of a.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!