MOD bug? Or something else?

2 visualizzazioni (ultimi 30 giorni)
Dr. Seis
Dr. Seis il 4 Ott 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?

Risposta accettata

Matt Fig
Matt Fig il 4 Ott 2012
Modificato: Matt Fig il 4 Ott 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 Commento
Dr. Seis
Dr. Seis il 4 Ott 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

Accedi per commentare.

Più risposte (1)

Dr. Seis
Dr. Seis il 5 Ott 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

Categorie

Scopri di più su Introduction to Installation and Licensing in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by