# Why does linspace deliver unequal spacing?

17 views (last 30 days)
K E on 13 Aug 2015
Commented: Walter Roberson on 12 Sep 2020
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;
XRegular=linspace(min(XGlobal),max(XGlobal),27);
sprintf('%.20f\n', unique(diff(XRegular)))
ans =
3.83868769397494700000
3.83868769397495410000
3.83868769397495770000
3.83868769397496120000
3.83868769397497540000
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?

the cyclist on 13 Aug 2015
Edited: the cyclist on 13 Aug 2015
Did you actually use interp2, and it failed because of this, or was that more of a theoretical statement you made?
K E on 13 Aug 2015
Not listed in bug reports but upgrading to R2015b might be the workaround I need!

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?
Walter Roberson on 12 Sep 2020
Over sufficiently large ranges with sufficiently precise steps, it is not possible to generate exactly uniform spacing, due to how double precision numbers are stored. If your range crosses a power-of-2 boundary, then you must lose a bit of precision. There is no real way around this except to deliberately work on ranges based upon powers of two instead of on ranges based on decimal -- for example, work from 1024 to 2047 instead of 1000 to 2000.