Comparing floating point numbers
Problem
Comparing floating point numbers does not always work as you expect. For example:
0.3 == 3*.1
#> [1] FALSE
(0.1 + 0.1 + 0.1) - 0.3
#> [1] 5.551115e-17
x <- seq(0, 1, by=.1)
x
#> [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
10*x - round(10*x)
#> [1] 0.000000e+00 0.000000e+00 0.000000e+00 4.440892e-16 0.000000e+00 0.000000e+00
#> [7] 8.881784e-16 8.881784e-16 0.000000e+00 0.000000e+00 0.000000e+00
Solution
There is no universal solution, because this issue is inherent to the storage format for non-integer (floating point) numbers, in R and computers in general.
See this page for more information and workarounds:http://www.mathworks.com/support/tech-notes/1100/1108.html. This is written for Matlab, but much of it will be relevant for R as well.
当前内容版权归 cookbook-r.com 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 cookbook-r.com .