【问题标题】:Exactly storing large integers精确存储大整数
【发布时间】:2015-11-28 20:53:58
【问题描述】:

在 R 软件中

a <- 123456789123456789123456789
sprintf("%27f",a)
#[1] "123456789123456791337762816.000000"

我答错了。我想要准确的 a 值。

为什么系统显示a的错误值?

【问题讨论】:

  • 同时检查here
  • 正如this comment 中解释的(在重复问题下),使用gmp::as.bigz() 时不要忘记传递一个字符。

标签: r algorithm precision floating-point-precision


【解决方案1】:

您没有得到a 的确切值的原因是R 将它存储为双精度而不是整数。因为a 非常大,所以在分配a 时会发生一些舍入。

通常将事物存储为整数,您将在数字末尾使用L;类似:

a <- 12L
class(a)
# [1] "integer"

但是你的数字对于 R 中的标准整数来说太大了,你不得不使用双精度表示:

a <- 123456789123456789123456789L
# Warning message:
# non-integer value 123456789123456789123456789L qualified with L; using numeric value 
class(a)
# [1] "numeric"

您需要多精度才能准确存储这么大的整数。一种选择是gmp 包:

library(gmp)
a<-as.bigz("123456789123456789123456789")
a
# Big Integer ('bigz') :
# [1] 123456789123456789123456789

numerical mathematics CRAN task view 的“多精度算术和符号数学”子标题下提供了多精度算术的其他选项。

【讨论】:

  • a
  • @aarthi 您应该将每个存储为 bigz 然后相乘;类似prod(as.bigz(c(2, 3, 7, 43, 1807, 3263443)))
  • factorize(113423713055421844361000443) 和 factorize(113423713055421845118910464) 有相同的答案我该怎么做?
猜你喜欢
  • 2023-03-05
  • 2016-01-06
  • 2017-05-20
  • 2017-10-26
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 2021-02-18
  • 1970-01-01
相关资源
最近更新 更多