Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Rmpfr to round with precision in R

Tags:

rounding

r

mpfr

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?

like image 243
art Avatar asked Oct 20 '22 22:10

art


1 Answers

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:

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

Which is now correct.

like image 67
art Avatar answered Nov 15 '22 06:11

art