Stupid_Intern
Stupid_Intern

Reputation: 3450

How to get more precision in calculation

Currently R is rounding the calculation but if I want to get at least 120 digits post the decimal, how do I go about doing that in R?

 0.8/0.022332323

[1] 35.82252

Is there any default or setting so that it considers at least 120 digits post decimal? If not 120 can I make it at least 20 digits?

Upvotes: 1

Views: 620

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226007

R isn't rounding quite as much as you think it is. With base R, you can print 20 digits after the decimal place in this example (more precisely, you can print up to 22 significant digits; in this case 20 of them are after the decimal place). However, as commented by John Coleman, you won't get that much accuracy with R's double-precision floats (64 bits, of which 53 are mantissa, so we get 53/log2(10) = approx. 16 decimal places of precision).

Comparing base-R result to the Rmpfr results shown by @RuiBarradas, we see that they first diverge at digit 18.

print( 0.8/0.022332323, digits = 22)
## base-R 35.82251609024282856808
## Rmpfr  35.8225160902428288979534 ...
# digits  12 345678901234567890

Upvotes: 2

Rui Barradas
Rui Barradas

Reputation: 76402

Try package Rmpfr.

library(Rmpfr)

b <- ceiling(log2(10)*120)
x <- mpfr(0.8, precBits = b)
d <- mpfr(0.022332323, precBits = b)

x/0.022332323
1 'mpfr' number of precision  399   bits 
#[1] #35.822516090242828897953439868674559527396865046088517580669608395416394154166154302983768871199759705245811245184299832707

identical(x/0.022332323, x/d)
#[1] TRUE

Upvotes: 4

Related Questions