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 ?