I'm trying to use the Rmpfr
library with the round()
function to apply the round half to even rule and achieve correct results, without errors due the finite precision of float point values, as described here.
So far, this is what I've 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 don't get the desired results:
round2(1.152, 2)# Should be 1.15
#[1] "1.16"
Reading the Rmpfr
docs, at the roundMpfr()
function, it says:
The mpfr class group method Math2 implements a method for round(x, digits) which rounds to decimal digits.
But I can't figure how to use it.
How can I achieve desired round results using Rmpfr
?
Talking with the maintainer of
Rmpfr
about this issue, looks like it was a bug on the library.This commit fixed the issue.
After running
install.packages("Rmpfr")
to install the updated version of the library, now I get:Which is now correct.