MATLAB: Simple miscalculation: (1-0.95)*4000 = 2.000000000000002e+02

floating pointimprecisionprecisionroundingrounding error

Dear all,
I am using Matlab 2013a and I found this imprecision in a simple operation: (1-0.95)*4000. Matlab returned me 2.000000000000002e+02 instead of 200. Thus, I cannot access a vector position since it is not integer and when I use ceil Matlab returns 201.
Anyone has noticed this mistake before? Is it already corrected in new versions of Matlab?
Thanks, Bruno Fanzeres

Best Answer

This is not a bug, nor is it a mistake. This is the normal behavior of floating point numbers, and although it is not at all unexpected it often confuses beginners.
MATLAB uses floating point numbers which are stored with a finite number of binary digits. Because of the finite precision of these numbers, calculations often incur some rounding error, and it is your job as the programmer to account for this in the design of your algorithm.
If you really absolutely must avoid the precision limits of the standard number classes, then you basically have two choices:
  1. use a symbolic mathematics tool, such as the Symbolic Toolbox.
  2. use a higher precision toolbox, such as John D'Errico's HPF. Note that infinite precision is impossible.
For more information read these:
You might like to try James Tursa's FEX submission too: