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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Don’t compare floating point numbers for equality
The problem is that neither 0.3 nor 0.9 has an exact representation1 in the floating point format, and so when multiplying 0.3 * 3 you get a number that is very, very close to 0.9, and which will round to 0.9 for printing, but it isn’t 0.9.
And your 0.9 constant is also not precisely 0.9, and the two numbers are very slightly different.
Using exact equality comparisons for floating point numbers is usually a mistake in any language.
1. All integers up to about 252 have exact FP representations, but the fractions are composed of a sequence of 1 / 2n terms. Most decimal string fractions repeat in base 2.