seq和==运算符的神秘行为.精度问题? [英] Mysterious behaviour of seq and == operator. A precision issue?

查看:128
本文介绍了seq和==运算符的神秘行为.精度问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了功能seq的某种奇怪(或只是不期望的?)行为. 创建简单序列时,某些值不能与==运算符正确匹配. 看到这个最小的例子:

I've come across a somehow weird (or just not expected?) behaviour of the function seq. When creating a simple sequence some values cannot be matched correctly with the == operator. See this minimal example:

my.seq <- seq(0, 0.4, len = 5)
table(my.seq)                  # ok! returns  0 0.1 0.2 0.3 0.4 
                               #              1   1   1   1   1 

which(my.seq == 0.2)           # ok! returns  3
which(my.seq == 0.3)           # !!! returns  integer(0)

在手动创建序列时,它似乎可以工作,

When creating my sequence manually, it seems to work, though:

my.seq2 <- c(0.00, 0.10, 0.20, 0.30, 0.40)

which(my.seq2 == 0.3)           # ok! returns  4

您对此有何解释?我使用which(round(my.seq, 2) == 0.3)解决了问题,但我对引起问题的原因感兴趣.

Do you have any explanation for that? I solved the issue by using which(round(my.seq, 2) == 0.3) but I would be interested in what's causing the problem.

提前感谢您的评论.

推荐答案

计算机只是不能很好地表示浮点数.作为大多数人在计算机上处​​理数字的主要方式,电子表格隐藏这种情况的普遍趋势导致了许多问题.

Computers just don't represent floating point numbers well. The general tendencies of spreadsheets to hide this has, as the primary way most people deal with numbers on computers, lead to many problems.

永远不要与精确的浮点值匹配. R中有处理此问题的函数(例如all.equal),但我更喜欢以下内容.

Never match against exact floating point values. There are functions in R to deal with this (e.g. all.equal) but I prefer the following.

假设您有一个未知的浮点变量A,并且想查看它是否等于0.5.

Say you have an unknown floating point variable A and you want to see if it is equal to 0.5.

abs(A - 0.5) < tol

将公差设置为您需要的接近度0.5.例如,tol <- 0.0001对您可能很好.

Set tolerance to how close you need it to 0.5. For example, tol <- 0.0001 might be fine for you.

如果您的值看起来应该是整数,则取整.或者,如果您知道要测试的十进制级别,则可以舍入到该十进制级别.

If your values look like they should be integers just round. Or, if you know the decimal level that you want to test to then you can round to that decimal level.

这篇关于seq和==运算符的神秘行为.精度问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆