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?
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.
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.
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With