Inaccurate result when using mod(N,1) or rem(N,1), when N=9/(45*0.0001)

where N = i/(f*ts) : f=45, ts=0.0001, i =9; In this case: N=2000, then in while loop it calculates the remainder: rem(N,1) it must give zero but it gives 1 instead. By the way, I wrote 2000-N which should be zero, it gives me a very small number like -2.273736754432321e-13, this is considered by the remainder function as 1.

 Accepted Answer

It is not inaccurate. It simply reflects that you don't appreciate floating point arithmetic. Since you cannot represent numbers like 0.0001 exactly as a floating point number, what do you expect?
MATLAB uses a BINARY IEEE storage format, as do many other languages.
sprintf('%0.66f',0.0001)
ans =
0.000100000000000000004792173602385929598312941379845142364501953125
Just as you cannot represent 1/3 exactly as a decimal, so too you cannot represent 0.0001 exactly in binary. The above is what is effectively stored, when you type 0.0001 in MATLAB.
The point is, don't test for exact results in floating point computations. Instead, use methods that are robust to such problems. In some cases, this can be the gist of an entire numerical analysis course. If you expect an integer result from a computation like this,then round may be what you need. Or use a tolerance in tests. But we don't really have a clue as to what you are doing, since we are given no code.
Welcome to the wacky, wonderful, world of floating point arithmetic.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!