Question

Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to assert_in_delta(expected_float, actual_float, delta) from test/unit but returning Boolean?

Was it helpful?

Solution

(expected_float - actual_float).abs <= delta

OTHER TIPS

Depending on your application and what your floating point values are actually representing, it might make sense to convert them to Rationals with a given precision. Then direct comparisons will always behave correctly since Rationals are just two integers.

For instance, if you know you're dealing with US currency amounts, storing them as amount.to_r.round(2) allows for exact comparisons for equality.

Just a thought... not all non-integer values need to be inexactly-represented floats

you may also need a relative tolerance / delta calculation

http://realtimecollisiondetection.net/blog/?p=89

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top