Strange behavior when comparing floating points in rspec

3 of the following tests will occur:

  specify { (0.6*2).should eql(1.2) }
  specify { (0.3*3).should eql(0.3*3) }
  specify { (0.3*3).should eql(0.9) } # this one fails

Why? Is this a floating point problem or a ruby ​​or rspec problem?

+5
source share
2 answers

Do not compare floating point numbers for equality

The problem is that there is no exact representation of 1 in floating-point format in either 0.3 or 0.9 , and therefore when multiplied by 0.3 * 3 you get a number very, very close to 0.9, and which will round to 0.9 for print, but it is not 0.9.

And your 0.9 constant is also not exactly 0.9, and these numbers are very slightly different.

.


1. 2 52 FP-, 1/2 n. 2.

+8

rspec-2.1

specify { (0.6*2).should be_within(0.01).of(1.2) }

:

specify { (0.6*2).should be_close(1.2, 0.01) }
+12

All Articles