Rails: Testing your floating point numbers

You’re being a Good Software developer and diligently testing all your code, and lo and behold, you get this result to one of your tests:


1) Failure: ... <1.0> expected but was <1.0>

An annoying problem with floats that might look and for all practical purposes be equal, but internally as stored by the computer are not precisely equal.

You’re probably using:

1
assert_equal 1.0, a_value_expected_to_be_1.0

Instead, use:

1
assert_in_delta 1.0, a_value_expected_to_be_1.0, 0.000001

Though, you may also want to ask yourself if you really need to be using floating point numbers; but assuming that you do need them, assert_in_delta will compensate for the annoying fact that floating point numbers might not actually be precisely what you expect them to be.

0 Responses to “Rails: Testing your floating point numbers”


Comments are currently closed.



Fork me on GitHub