MOD bug? Or something else?

3 vues (au cours des 30 derniers jours)
Dr. Seis
Dr. Seis le 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?

Réponse acceptée

Matt Fig
Matt Fig le 4 Oct 2012
Modifié(e) : Matt Fig le 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 commentaire
Dr. Seis
Dr. Seis le 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

Connectez-vous pour commenter.

Plus de réponses (1)

Dr. Seis
Dr. Seis le 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;
answer = builtin('mod',X,Y);
end
*Note: I am dealing with numbers with less than 7 significant digits

Catégories

En savoir plus sur Introduction to Installation and Licensing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by