# MOD bug? Or something else?

10 views (last 30 days)
Dr. Seis on 4 Oct 2012
Seems to be a bug in MOD. The values inside the range from 0 to 1 that should result in MOD of 0 (or 0 to machine precision) for the example below (i.e., 0.4 and 0.8) are no where near 0.
>> [-2:.2:2;mod(-2:.2:2,.4)]'
ans =
-2.0000 0
-1.8000 0.2000
-1.6000 0
-1.4000 0.2000
-1.2000 0
-1.0000 0.2000
-0.8000 0.0000
-0.6000 0.2000
-0.4000 0.0000
-0.2000 0.2000
0 0
0.2000 0.2000
0.4000 0.4000
0.6000 0.2000
0.8000 0.4000
1.0000 0.2000
1.2000 0
1.4000 0.2000
1.6000 0
1.8000 0.2000
2.0000 0
I am running R2011a on UNIX... anyone else encounter this problem?

Matt Fig on 4 Oct 2012
Edited: Matt Fig on 4 Oct 2012
Floating point arithmetic.... Look closely at the numbers.
x = [-2:.2:2];
fprintf('%16.16f\n',x)
You can read more about it here.
##### 1 CommentShowHide None
Dr. Seis on 4 Oct 2012
Yep... I was thinking this had nothing to do with floating point stuff. But if the value was very close to 0.4 (i.e., 0.4 +/- epsilon), the behavior of MOD would be very different if it was +epsilon versus -epsilon.
mod(0.39999999999,0.4) = 0.39999999999
vs.
mod(0.40000000001,0.4) = 0.00000000001
Looks like I will need to overload MOD

### More Answers (1)

Dr. Seis on 5 Oct 2012
This overloaded MOD function seems to overcome my issue:
function answer = mod(X,Y)
tol = 1e7;
X = round(X*tol)/tol;
Y = round(Y*tol)/tol;
end
*Note: I am dealing with numbers with less than 7 significant digits