0

Why does this simple statement evaluate to FALSE in R?

mean(c(7.18, 7.13)) == 7.155

Furthermore, what do I have to do in order to make this a TRUE statement? Thanks!

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
user3624032
  • 59
  • 1
  • 5

2 Answers2

3

It's probably due to small rounding error. Rounding to the third decimal place shows that they are equal:

round(mean(c(7.18, 7.13)), 3) == 7.155

Generally, don't rely on numerical comparisons to give expected logical outputs :)

rbatt
  • 4,677
  • 4
  • 23
  • 41
3

Floating point arithmetic is not exact. The answer to this question has more information.

You can actually see this:

> print(mean(c(7.18,7.13)), digits=16)
[1] 7.154999999999999
> print(7.155, digits=16)
[1] 7.155

In general, do not compare floating point numbers for equality (this applies to pretty much every programming language, not just R).

You can use all.equal to do an inexact comparison:

> all.equal(mean(c(7.18,7.13)), 7.155)
[1] TRUE
Community
  • 1
  • 1
T.C.
  • 133,968
  • 17
  • 288
  • 421