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

2 views (last 30 days)
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

Accepted Answer

Stephen23
Stephen23 on 27 May 2015
Edited: Stephen23 on 27 May 2015
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:
  1 Comment
Titus Edelhofer
Titus Edelhofer on 27 May 2015
And regarding the concrete problem: use round instead of ceil to get to the 200 ...
Titus

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!