Using Rmpfr to Round Up to R

I am trying to use the Rmpfr library with the round() function to apply the round half to even rule and achieve the correct results, without errors due to the finite accuracy of the float values, as described here .

So far, this is what I have achieved:

 library(Rmpfr) x <- c(1.225, 1.2225, 1.22225, 1.222225) n <- c(2, 3, 4, 5) round2 <- function(x, n){ sprintf(paste("%#.", n, "f", sep=""), round(mpfr(as.character(x), 200), n)) } mapply(round2, x, n) #[1] "1.22" "1.222" "1.2222" "1.22222" 

But in some cases, I do not get the desired results:

 round2(1.152, 2)# Should be 1.15 #[1] "1.16" 

Rmpfr in the roundMpfr() function, he says:

The mpfr group group method Math2 implements the round (x, digit) method, which is rounded to decimal digits.

But I can’t figure out how to use it.

How to achieve the desired round results with Rmpfr ?

+5
source share
1 answer

Speaking with the accompanying Rmpfr about this problem, it looks like it was a bug in the library.

This fix fixed the problem.

After running install.packages("Rmpfr") to install the updated version of the library, now I get:

 library(Rmpfr) sprintf("%#.2f", round(mpfr(1.152, 200),2)) #[1] "1.15" 

Now this is correct.

+3
source

Source: https://habr.com/ru/post/1207077/


All Articles