Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare Floats with delta?

Tags:

ruby

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?

like image 313
MarekBaron Avatar asked Oct 27 '08 08:10

MarekBaron


2 Answers

(expected_float - actual_float).abs <= delta
like image 84
ysth Avatar answered Nov 10 '22 09:11

ysth


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

like image 40
cvkline Avatar answered Nov 10 '22 10:11

cvkline