MATLAB Answers

Why does linspace deliver unequal spacing?

9 views (last 30 days)
K E on 13 Aug 2015
Commented: K E on 14 Aug 2015
I thought linspace was supposed to deliver a vector with perfectly even spacing, but there seems to be a slight difference in spacing, for example:
XGlobal = sort(rand(1,100))*100 - 50;
sprintf('%.20f\n', unique(diff(XRegular)))
ans =
You can see the last few digits differ. That means that, for example, interp2 with cubic interpolation won't work because it requires evenly spaced vectors. What is the workaround?


Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 13 Aug 2015
Edited: the cyclist on 13 Aug 2015
This is a result of computing in floating point arithmetic. Here is one of many possible starting points to read about this.
Did you actually use interp2, and it failed because of this, or was that more of a theoretical statement you made?


Show 2 older comments
K E on 13 Aug 2015
R2015a. Sorry for missing YPointOrigin, corrected now.
the cyclist
the cyclist on 13 Aug 2015
I forgot I am using the R2015b pre-release. That version does not throw the warning. R2015a does throw the warning for me, too.
This suggests to me that this might be a listed bug. You could try searching the bug listing online for some recourse.
K E on 13 Aug 2015
Not listed in bug reports but upgrading to R2015b might be the workaround I need!

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 13 Aug 2015
Consider for example, diff((1:3)/3,2) = 5.55111512312578e-17 indicating that (2/3 - 1/3) is not exactly equal to (3/3 - 2/3). And
cumsum(1/3*ones(1,10)) - (1:10)/3
is non-zero in positions 5, 6, and 7, indicating that adding 1/3 five times does not give the same result as if you had calculated 5/3 directly.
linspace has to choose one way of calculating the values. Whichever way it chooses is going to be "wrong" by some measure. If it makes the intervals exactly equal then there must be cumulative error. Do you want the "add 1/3 five times" value where the intervals are equal, or do you want the "5/3" value where the values are more precise but the intervals might not be exactly the same?

  1 Comment

K E on 14 Aug 2015
Thanks. I have come to see that the underlying issue isn't that linspace is slightly unevenly spaced, but that Matlab functions like interp2's cubic option that require 'evenly' spaced inputs should tolerate very small amounts of unevenness.

Sign in to comment.

Sign in to answer this question.