R:大数字错误的算术

发布于 2025-01-21 23:19:53 字数 283 浏览 1 评论 0原文

当R执行简单算术的大数字时,我在R中遇到了一个问题。有人可以解释发生的事情以及如何工作吗?

> a <- 51569
> b <- a + 6924851946518374722
> b
[1] 6924851946518425600 # problem is visible here already
> c <- b - 6924851946518374722
> c
[1] 51200

因此,添加大数字时的错误为469。为什么?

I encountered a problem in R when it's performing simple arithmetic for big numbers incorrectly. Can someone explain what's happening, and how to work around?

> a <- 51569
> b <- a + 6924851946518374722
> b
[1] 6924851946518425600 # problem is visible here already
> c <- b - 6924851946518374722
> c
[1] 51200

So there's an error of 469 when adding the big number. Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心碎无痕… 2025-01-28 23:19:53

R使用双精度浮点来表示值。精度取决于您的计算机。在我的Intel Machine上,带有IEEE双打,我获得了52位精确度:

> options(digits=22)
> (0:1) + 2^52
[1] 4503599627370496 4503599627370497
> (0:1) + 2^53
[1] 9007199254740992 9007199254740992

R uses double-precision floating-point to represent values. The precision depends on your machine. On my Intel machine with IEEE doubles, I get 52 bits of precision:

> options(digits=22)
> (0:1) + 2^52
[1] 4503599627370496 4503599627370497
> (0:1) + 2^53
[1] 9007199254740992 9007199254740992
橙味迷妹 2025-01-28 23:19:53

r有一个包装GMP的软件包,GNU多个精度库:

cran:ran> cran:r GMP手册

library(gmp)
a <- as.bigz("51569")
b <- a + as.bigz("6924851946518374722")
c <- b - as.bigz("6924851946518374722")
c

Big Integer ('bigz') :
[1] 51569

正如评论中指出的那样,报价是必要的。

as.bigz(6924851946518374722) # Does not work as intended
Big Integer ('bigz') :
[1] 6924851946518374400

因为否则r将参数转换为双重,在转换为bigz之前丢失精度。

还请注意,R尚未支持64位整数,例如

[1] 4294967296L
Warning message:
non-integer value 4294967296 qualified with L; using numeric value 

R has a package that wraps GMP, the gnu multiple precision library:

CRAN: R gmp manual

library(gmp)
a <- as.bigz("51569")
b <- a + as.bigz("6924851946518374722")
c <- b - as.bigz("6924851946518374722")
c

Big Integer ('bigz') :
[1] 51569

As pointed out in a comment, the quotes are necessary.

as.bigz(6924851946518374722) # Does not work as intended
Big Integer ('bigz') :
[1] 6924851946518374400

because otherwise R converts the argument to a double, losing precision before converting to bigz.

Note also that R does not yet support 64 bit integers, e.g.

[1] 4294967296L
Warning message:
non-integer value 4294967296 qualified with L; using numeric value 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文