Cumsum resulting in cumulative error compared to looping
2 views (last 30 days)
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?
0 Comments
Accepted Answer
Matt J
on 23 Aug 2023
Edited: Matt J
on 23 Aug 2023
Is this just a result of the loss of precision as the vector index increases?
Yes The error will accumulate more with cumsum(), since with colon() each element of the final vector is the result of just one operation.
Any way to avoid this when using cumsum?
Yes, as below. However, your example represents a case where it would never make sense to use cumsum, so it's hard to know if this solution solves your original problem.
d = 0.999999;
n = 1e6;
a = cumsum(ones(1,n))*d;
b = (1:n)*d;
figure; plot(a-b)
More Answers (0)
See Also
Categories
Find more on Logical 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!
