s-news
[Top] [All Lists]

Re: strange round / signif behaviour

To: s-news@wubios.wustl.edu, pierre.delfosse@centexbel.be
Subject: Re: strange round / signif behaviour
From: Alan Zaslavsky <zaslavsk@hcp.med.harvard.edu>
Date: Wed, 25 Jul 2001 09:13:06 -0400 (EDT)
> From: Pierre Delfosse <pierre.delfosse@centexbel.be>
> To: s-news@wubios.wustl.edu
> Subject: [S] strange round / signif behaviour
> Date: Wed, 25 Jul 2001 14:30:53 +0200
> 
> Dear S+ users,
> 
> S+ 2000 under W98 does not always "round" nor "signif" correctly. For
> example,
> 
>       > round(0.81,2)
>       [1] 0.8100000000000001
>       > signif(0.81,2)
>       [1] 0.8100000000000001
> 
> (there are other examples).
> 
> Is this a known bug, possibly computer dependant? How can I avoid this
> behaviour?

Not a bug; it is computer dependent only in the sense that some conceivable
computer (not any in common use since binary-coded-decimal went out of style in 
the 1960's) would not have this problem.  

The number you are calculating is 0.8, but because this is not an integer
times a power of 2, it does not have an exact representation in binary
floating point.  0.8100000000000001 is as close as you can get (printed
to that degree of precision).  If you are trying to get a clean printed
representation, you should not be printing more digits than the accuracy
of the internal representation of the number.  For ordinary printing the
"digits" option give a more reasonable rounding (as long as you set it to
something reasonable (default value is 7), but with some output functions
(notably "cat")  you need to use format() to explicitly control the
number of digits printed.

Many other questions raised on this list concerning exact comparisons stem
from exactly the same type of issue.  Unless you are working with integers,
you should expect some small amount of noise in your results.

<Prev in Thread] Current Thread [Next in Thread>