Cumsum resulting in cumulative error compared to looping
Show older comments
I'm having trouble understanding why the output for these two lines are not identical:
d = 0.999999;
n = 1e6;
a = cumsum(repelem(d,n));
b = (1:n)*d;
figure; plot(a-b)
numerically I would expect them to be the same:
a = [0.999999 , (0.999999 + 0.999999), (0.999999 + 0.999999 + 0.999999 ) ,...]
b = [0.999999*1, 0.999999*2, ...]
Using a loop to compute the summation gives the same results as cumsum. Is this just a result of the loss of precision as the vector index increases? Any way to avoid this when using cumsum?
Accepted Answer
More Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
