[R] Interesting quirk with fractions and rounding
Paul Johnson
pauljohn32 at gmail.com
Thu Apr 20 23:56:21 CEST 2017
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.
More information about the R-help
mailing list