[R] rounding down with as.integer

Duncan Murdoch murdoch.duncan at gmail.com
Thu Jan 1 17:10:07 CET 2015


On 31/12/2014 8:44 PM, David Winsemius wrote:
> 
> On Dec 31, 2014, at 3:24 PM, Mike Miller wrote:
> 
>> This is probably a FAQ, and I don't really have a question about it, but I just ran across this in something I was working on:
>>
>>> as.integer(1000*1.003)
>> [1] 1002
>>
>> I didn't expect it, but maybe I should have.  I guess it's about the machine precision added to the fact that as.integer always rounds down:
>>
>>
>>> as.integer(1000*1.003 + 255 * .Machine$double.eps)
>> [1] 1002
>>
>>> as.integer(1000*1.003 + 256 * .Machine$double.eps)
>> [1] 1003
>>
>>
>> This does it right...
>>
>>> as.integer( round( 1000*1.003 ) )
>> [1] 1003
>>
>> ...but this seems to always give the same answer and it is a little faster in my application:
>>
>>> as.integer( 1000*1.003 + .1 )
>> [1] 1003
>>
>>
>> FYI - I'm reading in a long vector of numbers from a text file with no more than three digits to the right of the decimal.  I'm converting them to integers and saving them in binary format.
>>
> 
> So just add 0.0001 or even .0000001 to all of them and coerce to integer.

I don't think the original problem was stated clearly, so I'm not sure
whether this is a solution, but it looks wrong to me.  If you want to
round to the nearest integer, why not use round() (without the
as.integer afterwards)?  Or if you really do want an integer, why add
0.1 or 0.0001, why not add 0.5 before calling as.integer()?  This is the
classical way to implement round().

To state the problem clearly, I'd like to know what result is expected
for any real number x.  Since R's numeric type only approximates the
real numbers we might not be able to get a perfect match, but at least
we could quantify how close we get.  Or is the input really character
data?  The original post mentioned reading numbers from a text file.

Duncan Murdoch



More information about the R-help mailing list