
Title | Comparing floating-point values (the float function) | |
Author | Jeremy B. Wernow, StataCorp |
If you try to compare the value of a floating-point variable to a known value, you may not get the results you expect.
. list +-----+ | x | |-----| 1. | 7.3 | 2. | 7.3 | 3. | 7.3 | +-----+ . list if x==7.3 . describe Contains data obs: 3 vars: 1 size: 24 (99.9% of memory free) ----------------------------------------------------------------------- storage display value variable name type format label variable label ------------------------------------------------------------------------ x float %9.0g ------------------------------------------------------------------------ Sorted by: Note: dataset has changed since last saved
This occurs because of a binary rounding error. There is no way to exactly represent most noninteger numbers using a binary system. To get around this, you can use the float() function (not the cast type). To round the above expression to its floating-point value, type
. list if x ==float(7.3) +-----+ | x | |-----| 1. | 7.3 | 2. | 7.3 | 3. | 7.3 | +-----+
To read more about floating-point precision, see [U] 13.12 Precision and problems therein.