Bug 15624 - Don't use floor(x+0.5)
Summary: Don't use floor(x+0.5)
Alias: None
Product: R
Classification: Unclassified
Component: Accuracy (show other bugs)
Version: R-devel (trunk)
Hardware: Other All
: P5 normal
Assignee: R-core
Depends on:
Reported: 2013-12-30 21:13 UTC by M Welinder
Modified: 2014-01-10 16:15 UTC (History)
0 users

See Also:

Output of grep -Hrin floor.*\\.5 (5.28 KB, text/plain)
2014-01-10 16:15 UTC, Roby Joehanes

Note You need to log in before you can comment on or make changes to this bug.
Description M Welinder 2013-12-30 21:13:12 UTC
For purposes of rounding a floating-point number to the nearest integer,
this does not work:

    x = floor (x + 0.5);

The proper thing to do is rint, round, or nearbyint -- with some consideration
as to which one to use if x might be negative.  nearbyint is likely the one
to use most of the time.

The problem affects two classes of numbers:

(a) nextafter(0.5,0)      -- the number just below 0.5 gets rounded to 1.
(b) +- (2^52+odd)         -- adding 0.5 really adds 1

This is visible from the R command line:

> dpois(2^52,1,1)
[1] -1.578226e+17               <-- good
> dpois(2^52+1,1,1)
[1] -Inf                        <-- bad
Warning message:
In dpois(2^52 + 1, 1, 1) : non-integer x = 4503599627370497.000000
Comment 1 Brian Ripley 2014-01-05 13:41:53 UTC
You do not mention which of the many uses in the R sources you have in mind: helpful people do.

nearbyint and rint have only become available recently (I am not sure all R platforms have them both yet).

This particular case is fixed.
Comment 2 Roby Joehanes 2014-01-10 16:15:26 UTC
Created attachment 1553 [details]
Output of grep -Hrin floor.*\\.5

Here are some additional instances. This is checked against R-patched_2014-01-08_r64705.tar.gz. I ran the following command:
grep -Hrin floor.*\\.5 *

Attached please find is the output. Hope this helps.