降低R中的双精度 [英] Reducing Precision in Doubles in R

查看:63
本文介绍了降低R中的双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,通过使用基本R工具而不使用C或C ++来始终忽略R中浮点数之间的小差异(根据IEC 60559,这是双精度浮点数).换句话说,我想舍入"双精度浮点数的有效部分,以使类似这样的结果返回TRUE而不是FALSE:

I'm looking for a way to consistently ignore small differences between floating point numbers in R (these are double precision floating points as per IEC 60559), by using base R tools and without resorting to C or C++. In other words, I would like to "round" the significand portion of the double precision floating point numbers such that things like this return TRUE instead of FALSE:

1.45 - .55 == 2.45 - 1.55
## [1] FALSE

类似的东西:

round_significand(1.45 - .55, bits=48) == round_significand(2.45 - 1.55, bits=48)
## [1] TRUE

简单的round不起作用,因为我们需要舍入的级别取决于数字的大小.

A simple round doesn't work because the level to which we need to round depends on the magnitude of the number.

data.table在内部从?setNumericRounding执行某种操作:

data.table does something of the sort internally, from ?setNumericRounding:

计算机不能表示某些浮点数(例如 0.6)精确地使用基数2.这会导致意外行为 在连接或分组数字"类型的列时;即双", 请参见下面的示例.如果不希望这样做,请使用data.table 允许将此类数据四舍五入到大约11s.f.这是 在很多情况下,很多数字.这是通过四舍五入来实现的 有效位的最后2个字节.其他可能的值为1个字节 舍入或不舍入(全精度,默认).

Computers cannot represent some floating point numbers (such as 0.6) precisely, using base 2. This leads to unexpected behaviour when joining or grouping columns of type 'numeric'; i.e. 'double', see example below. In cases where this is undesirable, data.table allows rounding such data up to approximately 11 s.f. which is plenty of digits for many cases. This is achieved by rounding the last 2 bytes off the significand. Other possible values are 1 byte rounding, or no rounding (full precision, default).

我正在研究一种将所有内容缩放为十进制数字x的hack实现,这样floor(log10(x)) == 1并对其进行四舍五入,例如:

I'm working on a hack implementation that scales everything to be a decimal number x such that floor(log10(x)) == 1 and rounds that, e.g.:

rnd_sig <- function(x, precision=10) {
  exp <- floor(log10(abs(x)))
  round(x * 10 ^ (-exp), precision) / 10 ^ (-exp)
}

但是我对浮点数的了解还不足以确保它是安全的(或何时安全,而不是安全的).

but I don't know enough about floating point numbers to be sure this is safe (or when it is safe, and not).

推荐答案

一种可能的解决方案是使用signif,该功能与round相关并且包含在同一帮助文件中. 的帮助文件,说

One possible solution is to use signif, a function related to round and included in the same help file. The help file from ?signif, says

signif将其第一个参数中的值四舍五入为指定的有效数字位数.

signif rounds the values in its first argument to the specified number of significant digits.

四舍五入将其第一个参数中的值四舍五入到指定的小数位数(默认为0).

round rounds the values in its first argument to the specified number of decimal places (default 0).

所以看来signif可能与您的问题更为紧密.

So it appears that signif may be more closely related to your problem.

这篇关于降低R中的双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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