简体   繁体   English

如何在R中保持浮点精度?

[英]how to keep floating point precision in R?

I assign a floating point number to a variable in R.我为 R 中的变量分配了一个浮点数。

eg例如

k <- 1200.0000002161584854

I got我有

 > k
 [1] 1200
 > k+0.00000001
 [1] 1200

How to keep the precision of k ?如何保持 k 的精度?

I have read some posts here, but, I do not find a solution.我在这里阅读了一些帖子,但是,我没有找到解决方案。

In addition to the above answers, notice that the value of k will be different than what you originally assigned it.除了上述答案之外,请注意k的值将与您最初分配的值不同。 It will only have about 15 or 16 digits of precision (most of the time this is more than you will need).它只有大约 15 或 16 位的精度(大多数情况下这超出了您的需要)。

k <- 1200.0000002161584854
sprintf('%1.29f',k)
 "1200.00000021615846890199463814497"

Note that there are libraries where you can increase precision, such as gmp , but they are designed around integers.请注意,有些库可以提高精度,例如gmp ,但它们是围绕整数设计的。

First, to make sure that you actually lost precision, print it with sprintf() or use print() with the digits argument set to something high (but no greater than 22) to see more digits:首先,为了确保您确实失去了精度,请使用sprintf()打印它或使用将digits参数设置为高(但不大于 22)的print() ) 以查看更多数字:

k <- 1200.0000002161584854
k
# [1] 1200
sprintf("%4.20f", k)
# [1] "1200.00000021615846890199"

See this question why there is a difference between what I set k to be and what was printed.请参阅这个问题,为什么我设置的k与打印的内容之间存在差异。

Now, we can add 0.00000001 :现在,我们可以添加0.00000001

m <- k + 0.00000001
m
# [1] 1200
sprintf("%4.20f", m)
# [1] "1200.00000022615836314799"

We see that the values are actually different:我们看到值实际上是不同的:

sprintf("%4.20f", k - m)
# [1] "-0.00000000999989424599"

We just don't see the difference when we print because the without telling R otherwise, it will not show all of the digits.我们只是在打印时看不到差异,因为不告诉 R 否则它不会显示所有数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM