First circle of R hell. 0.1 != 0.3/3 [duplicate]

2020-04-04 10:00发布

Possible Duplicate:
Numeric comparison difficulty in R

Hello All,

According to "R Inferno" paper. I'm right now in the first circle of R hell. This is where pagans expect 0.1 == 0.3/3. Paper recommends using all.equal function for such cases, however I need to check ">=" or "<=" conditions. With current example on of them fail:

> .1 >= .3/3
[1] TRUE
> .1 <= .3/3
[1] FALSE

Is there a similar function to all.equal that checks inequalities?

Thank you,

Ilya

4条回答
聊天终结者
2楼-- · 2020-04-04 10:29

Please see the R FAQ entry Why doesn't R think these numbers are equal and the references therein.

查看更多
等我变得足够好
3楼-- · 2020-04-04 10:29

You could try judicious use of zapsmall() which seems to give the behavior you are looking for. I don't know if this works in all situations. e.g.,

.1 >= zapsmall(.3/3)
[1] TRUE
> .1 <= zapsmall(.3/3)
[1] TRUE
查看更多
倾城 Initia
4楼-- · 2020-04-04 10:35

See these questions:

Generally speaking, you can deal with this by including a tolerance level as per the second link above.

查看更多
forever°为你锁心
5楼-- · 2020-04-04 10:47

The main test of all.equal is whether abs(x-y) < tolerance for some values x and y and some small tolerance. Equivalent inequality tests would check:

x <= y:         x-y < tolerance
x < y:          x-y < -tolerance
x >= y:         x-y > -tolerance
x > y:          x-y > tolerance
查看更多
登录 后发表回答