MOD bug? Or something else?

2 Ansichten (letzte 30 Tage)
Dr. Seis
Dr. Seis am 4 Okt. 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?

Akzeptierte Antwort

Matt Fig
Matt Fig am 4 Okt. 2012
Bearbeitet: Matt Fig am 4 Okt. 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 Kommentar
Dr. Seis
Dr. Seis am 4 Okt. 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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Dr. Seis
Dr. Seis am 5 Okt. 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

Kategorien

Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by