I assign a floating point number to a variable in R.

e.g.

k <- 1200.0000002161584854

I got

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

How to keep the precision of 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. It will only have about 15 or 16 digits of precision (most of the time this is more than you will need).

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.

其他提示

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:

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.

Now, we can add 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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top