-3

Does the last statement in this series of statements make logical sense to anybody else? R seems to give similar results for a small subset of possible sums of decimals under 1. I cannot recall any basic mathematical principles that would make this true, but it seems to be unlikely to be an error.

> 0.4+0.6
[1] 1
> 0.4+0.6==1.0
[1] TRUE
> 0.3+0.6
[1] 0.9
> 0.3+0.6==0.9
[1] FALSE
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880

2 Answers2

1

Try typing 0.3+0.6-0.9, on my system the result is -1.110223e-16 this is because the computer doesn't actually sum them as decimal numbers, it stores binary approximations, and sums those. And none of those numbers can be exactly represented in binary, so there is a small amount of error present in the calculations, and apparently it's small enough not to matter in the first one, but not the second.

genisage
  • 1,159
  • 7
  • 17
1

Floating point arithmetic is not exact, but the == operator is. Use all.equal to compare two floating point values in R.

isTRUE(all.equal(0.3+0.6, 0.9))

You can also define a tolerance when calling all.equals.

isTRUE(all.equal(0.3+0.6, 0.9, tolerance = 0.001))
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880