[R] Using Rmpfr to round with precision in R
Artur Augusto
arturaugusto at gmail.com
Wed Nov 19 18:26:12 CET 2014
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.
Example of problem:
round(1.225,2)
#[1] 1.23
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 rounded results?
Artur
More information about the R-help
mailing list