-1

Possible Duplicate:
In R, what is the difference between these two?
floating point issue in R?

This is part of a code I created. I spend days looking for the problem when finally realized that a comparison that should be TRUE was being calculated by R as FALSE. I'm using R 2.14.2 64 bits on windows. This is the code to reproduce the problem.

concList= c(1.15, 1.15, 1.15 ,1.15 ,1.15 ,1.15 )
concList=concList-0.4
a=sum(concList)
b=length(concList)*0.75
str(a)
str(b)
print(a==b)

The last print will result in FALSE even thou they are shown as exactly the same number. I tough this could be some problem on the floating point numerical representation of R, so I added the code below which solves the problem.

a=round(a,1)
b=round(b,1)
print(a==b)

My question is, is there any more elegant solution? Is this a bug that should be reported?

Thanks for your time.

Community
  • 1
  • 1
Tiago Zortea
  • 159
  • 1
  • 6

1 Answers1

6

Because they aren't exactly the same number. They differ by a very small amount due to the computer's representation of numbers, also known as floating point errors:

> a - b
[1] -8.881784e-16

Jon Skeet has an excellent blog post on this issue, which pops up on Stack Overflow with some regularity.

As @mrdwab suggests in the comments, you should use all.equal(a, b) to test for near equality.

Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187