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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to