MATLAB Answers


Why does linspace deliver unequal spacing?

さんによって質問されました 2015 年 8 月 13 日
最新アクティビティ K E
さんによって コメントされました 2015 年 8 月 14 日
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?

  0 件のコメント

サインイン to comment.


2 件の回答

the cyclist
Answer by the cyclist
on 13 Aug 2015
Edited by the cyclist
on 13 Aug 2015
 Accepted Answer

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?

  5 件のコメント

on 13 Aug 2015
R2015a. Sorry for missing YPointOrigin, corrected now.
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.
on 13 Aug 2015
Not listed in bug reports but upgrading to R2015b might be the workaround I need!

サインイン to comment.

Walter Roberson
Answer by 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 件のコメント

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.

サインイン to comment.

Translated by