Cumsum resulting in cumulative error compared to looping

2 views (last 30 days)
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

Matt J
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)
  1 Comment
Tyler Foster
Tyler Foster on 23 Aug 2023
Appreciate the reply. I was trying to make my example simple enough. In my actual code cumsum gets called with an argument calculated elsewhere that may or may not be repeating values.
I appreciate that your solution wont apply but it does answer the question of "why is cumsum different".

Sign in to comment.

More Answers (0)

Products


Release

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!