[R] Using Rmpfr to round with precision in R
Artur Augusto
arturaugusto at gmail.com
Sat Nov 29 19:42:04 CET 2014
Thanks Martin, looks like the update fixed the issue.
The round2 function is just to format the output.
now I can get the correct result:
library(Rmpfr)
sprintf("%#.2f", round(mpfr(1.152, 200),2))
round2(1.152, 2)
#[1] "1.15"
Artur
2014-11-27 7:10 GMT-02:00 Martin Maechler <maechler at stat.math.ethz.ch>:
>>>>>> Artur Augusto <arturaugusto at gmail.com>
>>>>>> on Wed, 19 Nov 2014 15:26:12 -0200 writes:
>
> > 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"
>
> The above round2() function is really pretty strange [what do you really want?]
> but below, you have a very good point :
>
> > 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:
>
> Actually, roundMpfr() is *not* used by round(<mpfr>, *)
> It has somewhat different semantics. That's why I used a new
> function name, roundMpfr(), whereas the round() method for
> "mpfr" objects is what you get from
>
> selectMethod(round, "mpfr")
>
> > The mpfr class group method Math2 implements a method for round(x,
> > digits) which rounds to decimal digits.
>
> Indeed... and that is different from the roundMpfr() as
> mentioned above.
>
> > But I can't figure how to use it.
>
> > How can I achieve desired rounded results?
> > Artur
>
> Wait a day or two [depending on how quickly the new Rmpfr version 0.5-7
> gets published on CRAN], and update your Rmpfr package.
> The problem is fixed in Rmpfr 0.5-7.
>
> If you had CC'ed your e-mail to
> maintainer("Rmpfr")
> I would have heard of the problem earlier and almost surely
> have fixed it earlier.
>
> Best regards,
> Martin Maechler (maintainer of 'Rmpfr').
More information about the R-help
mailing list