[R] question about precision, floor, and powers of two.

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Nov 4 18:46:12 CET 2005


On Fri, 4 Nov 2005, Thomas Lumley wrote:

> On Fri, 4 Nov 2005, Uwe Ligges wrote:
>
>> Dr Carbon wrote:
>>
>>> At the risk of being beaten about the face and body, can somebody explain
>>> why the middle example: log2(2^3); floor(log2(2^3)) is different than
>>> examples 1 and 3?
>>
>>
>> Because
>>
>>> log2(2^3) - 3
>> [1] -4.440892e-16
>>
>
>
> This is a less satisfactory answer than usual, because both 2^3 and
> log(2^3) are integers and thus exactly representable in the R numeric
> type.  You could reasonably expect log(8) to be exactly 2, just as sqrt(4)
> is exactly 2.
>
> The problem is that we compute all logarithms via the natural log, and
> this introduces the problem of limited precision.

Well, we _did_ (and as others have noted, most machines manage to get 
log(8) to be exactly 2).

R-devel now uses log2 for this, so

> log2(2^29) - 29
[1] 0


-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595




More information about the R-help mailing list