Erlang Central

Difference between revisions of "Floating Point Compare"

From ErlangCentral Wiki

Line 69: Line 69:

Revision as of 23:00, 3 September 2006


You want to compare two floating-point numbers and know if they are equal. Unfortunately, floating-point arithmetic is not precise so very few results will match exactly. Consequently, we usually want to compare floating point values up to a certain number of decimal places.


Erlang (unforunately) does not implement the full tower of numerics, which would provide built-in support for access to exact and inexact integers, bignum support, and a raft of other tools making this particular recipe somewhat unnecessary.

Consequently, we will implement a "fuzzy match" on two real numbers where the difference is below some epsilon threshhold.

In these cases, you can use floating-point byte strings to represent and compare numbers:

1> Aval = 8.001e-3 * 9.001e5.
2> Bval = 8.0011e-3 * 9.001e5.
3> Aval == Bval.
4> ABin = << Aval/float >>.
5> BBin = << Bval/float >>.
6> << ABinTest:3/binary, ARest:5/binary >> = ABin.
7> ABinTest.
8> << BBinTest:3/binary, BRest:5/binary >> = BBin.
9> BBinTest.
10> BinTest == BinTest2.
11> << ABinTest2:4/binary, ARest2:4/binary >> = ABin.
12> << BBinTest2:4/binary, BRest2:4/binary >> = BBin. 
13> ABinTest2 == BBinTest2.

Another option is to convert the numbers into strings and then compare the portions of the numbers of interest:

14> [Nsa]=io_lib:format("~.12f", [Aval]).
15> [NSB]=io_lib:format("~.12f", [Bval]).  
16> string:substr(NSAa, 1, 6) == string:substr(NSB, 1, 6).

It would obviously be better to make use of some (imaginary) Erlang bignum and exact integer facility to carry calculations through your programs with the highest level of precision. However, Erlang does not consistently provide the level of detail necessary for certain mathematical operations. Consequently, it is frequently useful to provide "fuzzy" matching on numerical terms. Hopefully this recipe can help deal with those situations.

A final thought:

20> Equal_to_digit = fun(Digit, Numa, Numb) ->                     
20> [N_a] = io_lib:format("~.12f", [Numa]),                   
20> [N_b] = io_lib:format("~.12f", [Numb]),   
20> string:substr(N_a, 1, Digit) == string:substr(N_b,1,Digit) end.
21> Equal_to_digit(6, Aval, Bval).

Note: Some error handling would obviously be necessary to handle cases where the digits are insufficient for the match.

See Also

Volume 2, Section 4.2.2 of The Art of Computer Programming