-1

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.

lmo
  • 37,904
  • 9
  • 56
  • 69
user3440244
  • 371
  • 1
  • 3
  • 15
  • We would probably be able to help you more easily if you told us why you need to control the relative error to a precision of 0.0000002/1200=1.7e-10. Remember that computers will always have errors in floating point arithmetic (see R FAQ 7.31). If you really need arbitrary precision, look at this and expect much slower speed: http://r.789695.n4.nabble.com/Arbitrary-Precision-Numbers-td855931.html If you are only concerned about printing to the console, look at `options()$digits`. – Stephan Kolassa Apr 04 '14 at 19:05

2 Answers2

1

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.

Max Candocia
  • 4,294
  • 35
  • 58
  • My concern is which value of m will be used for actual following calculation after m <- k + 0.00000001 ? 1200 or 1200.0000002161584854 ? Thanks ! – user3440244 Apr 04 '14 at 20:19
  • The value will add the 0.00000001 without fail. It won't display though unless you use sprintf or use something like `options(digits=20)` to change the number of digits displayed by default. However, the precision of the lower terms will be lousy. It's not an issue if you don't need those digits, but if you do, you should consider using a specialized library. – Max Candocia Apr 04 '14 at 20:48
0

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.

Community
  • 1
  • 1
Christopher Louden
  • 7,540
  • 2
  • 26
  • 29