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?> log2(2^2); floor(log2(2^2))[1] 2 [1] 2> log2(2^3); floor(log2(2^3))[1] 3 [1] 2> log2(2^4); floor(log2(2^4))[1] 4 [1] 4>DrC [[alternative HTML version deleted]]
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 see the R FAQ "Why doesn't R think these numbers are equal?". Uwe Ligges> >>log2(2^2); floor(log2(2^2)) > > [1] 2 > [1] 2 > >>log2(2^3); floor(log2(2^3)) > > [1] 3 > [1] 2 > >>log2(2^4); floor(log2(2^4)) > > [1] 4 > [1] 4 > > > DrC > > [[alternative HTML version deleted]] > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
Thomas Lumley
2005-Nov-04 17:02 UTC
[R] question about precision, floor, and powers of two.
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. -thomas
Prof Brian Ripley
2005-Nov-04 17:46 UTC
[R] question about precision, floor, and powers of two.
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