[R] Interesting quirk with fractions and rounding

William Dunlap wdunlap at tibco.com
Fri Apr 21 04:09:21 CEST 2017


Use all.equal(tolerance=0, aa, bb) to check for exact equality:

   > aa <- 100*(23/40)
   > bb <- (100*23)/40
   > all.equal(aa,bb)
   [1] TRUE
   > all.equal(aa,bb,tolerance=0)
   [1] "Mean relative difference: 1.235726e-16"
   > aa < bb
   [1] TRUE

The numbers there are rounded to 52 binary digits (16+ decimal digits) for
storage and rounding is not a linear or associative operation.  Think of
doing arithmetic by hand where you store all numbers, include intermediate
results, with only 2 significant decimal digits:
   (3 * 1) / 3 -> 3 / 3 -> 1
   3 * (1/3) -> 3 * 0.33 -> 0.99


Bill Dunlap
TIBCO Software
wdunlap tibco.com

On Thu, Apr 20, 2017 at 2:56 PM, Paul Johnson <pauljohn32 at gmail.com> wrote:

> Hello, R friends
>
> My student unearthed this quirk that might interest you.
>
> I wondered if this might be a bug in the R interpreter. If not a bug,
> it certainly stands as a good example of the dangers of floating point
> numbers in computing.
>
> What do you think?
>
> > 100*(23/40)
> [1] 57.5
> > (100*23)/40
> [1] 57.5
> > round(100*(23/40))
> [1] 57
> > round((100*23)/40)
> [1] 58
>
> The result in the 2 rounds should be the same, I think.  Clearly some
> digital number devil is at work. I *guess* that when you put in whole
> numbers and group them like this (100*23), the interpreter does
> integer math, but if you group (23/40), you force a fractional
> division and a floating point number. The results from the first 2
> calculations are not actually 57.5, they just appear that way.
>
> Before you close the books, look at this:
>
> > aa <- 100*(23/40)
> > bb <- (100*23)/40
> > all.equal(aa,bb)
> [1] TRUE
> > round(aa)
> [1] 57
> > round(bb)
> [1] 58
>
> I'm putting this one in my collection of "difficult to understand"
> numerical calculations.
>
> If you have seen this before, I'm sorry to waste your time.
>
> pj
> --
> Paul E. Johnson   http://pj.freefaculty.org
> Director, Center for Research Methods and Data Analysis
> http://crmda.ku.edu
>
> To write to me directly, please address me at pauljohn at ku.edu.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list