Reputation: 23
I would like to add precise numbers together, and get a precise result. I know that I need to set my desired digit length in the options. For example:
> options(digits=20)
> x <- 42.616999999999997 + 42.405999999999999 + 42.869
I expect to get an answer with the level of precision set. In the above case:
> x
[1] 127.89199999999999591
This result is duly produced on my personal computer, but I cannot replicate it on my work computer, which - with the exact same code and the exact same environment (no difference in packages) - produces the following result:
> x
[1] 127.892
I am unclear about what else could differ between my personal and work computer. It might be useful to know that my personal computer is running R version 3.6.2, while my work computer is running 3.4.2 (I cannot update it because of installation restrictions).
Thank you in advance for your help!
Upvotes: 1
Views: 78
Reputation: 132576
In help("options")
we read:
digits: controls the number of significant (see signif) digits to print when printing numeric values. It is a suggestion only. Valid values are 1...22 with default 7. See the note in print.default about values greater than 15.
Your value is greater than 15, so let's check the note in help("print.default")
:
Large number of digits
Note that for large values of digits, currently for digits >= 16, the calculation of the number of significant digits will depend on the platform's internal (C library) implementation of sprintf() functionality.
This explains why you observe different results on different computers. Indeed, on my system:
options(digits=20)
42.616999999999997 + 42.405999999999999 + 42.869
#[1] 127.892
However, you can enforce a specific number of digits after the decimal point by using the R function sprintf
:
sprintf("%.17f", 42.616999999999997 + 42.405999999999999 + 42.869)
#[1] "127.89199999999999591"
Note that all of this is only about how numbers are printed. Internally, R uses always double precision (please read this post to understand the consequences).
If you need more precise results you'd need to use arbitrary precision numbers, e.g., by using the R package Rmpfr.
Upvotes: 1