Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange behaviour when comparing floating points in rspec

the 3rd of the following tests fails:

  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 that? Is this a floating point issue or a ruby or rspec issue?

like image 430
Enceradeira Avatar asked Jun 05 '11 16:06

Enceradeira


People also ask

Why is it a problem to compare two floating point numbers?

Comparing for equality Floating point math is not exact. Simple values like 0.1 cannot be precisely represented using binary floating point numbers, and the limited precision of floating point numbers means that slight changes in the order of operations or the precision of intermediates can change the result.

Can float values be compared?

To compare two floating point values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.


1 Answers

As of rspec-2.1

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

Before that:

specify { (0.6*2).should be_close(1.2, 0.01) }
like image 96
David Chelimsky Avatar answered Oct 08 '22 04:10

David Chelimsky