[R] unexpected results in comparison (x == y)

cls59 chuck at sharpsteen.net
Thu Nov 5 03:57:28 CET 2009




Peter Tillmann wrote:
> 
> Dear readers of the list,
> 
> I have a problem a comparison of two data from a vector. The comparison
> yields FALSE but should be TRUE. I have checked for mode(), length() and
> attributes(). See the following code (R2.10.0):
> 
> *SNIP*
> 
>> ZZ[4]
> [1] 0.02
>> ZZ[5]
> [1] 0.02
>> ZZ[4] == ZZ[5]
> [1] FALSE
> 
> *SNIP*
> 
> 

This looks like a side effect of roundoff error due to the finite precision
of numbers stored by a computer.  There was a large discussion of this issue
on the list about two weeks ago, you could read the posts at: 

  http://old.nabble.com/Rounding-error-in-seq%28...%29-ts25686630.html

They may provide some insight.  The punchline is that:

  0.2 = 2 * (1/10)

And 1/10 is not representable as a form of:

  2^n

For some integer n. Therefore the number 0.2 cannot be represented exactly
in floating point arithmetic and so inconsistencies will occur-- as you just
observed.  It's one of those realities of computer science that always
catches us non-computer scientists by surprise.

Hope this helps!

-Charlie

-----
Charlie Sharpsteen
Undergraduate
Environmental Resources Engineering
Humboldt State University
-- 
View this message in context: http://old.nabble.com/unexpected-results-in-comparison-%28x-%3D%3D-y%29-tp26195749p26208361.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list