floating-point representation

Arndt Jonasson arndt@REDACTED
Fri Jun 8 14:05:30 CEST 2001


In article <a05100c02b745a9623c2b@[213.100.91.238]>,
david wallin <david@REDACTED> wrote:
>I tried to decipher my own mail and think some clarification might be 
>in order...
>
>
>>Hi all,
>>
>>I'm trying to create (32-bit) floats from binaries (using the bit syntax).
>>
>>Empirical tests showed this to be a naive idea :
>>
>>A = random:uniform(256),
>>B = random:uniform(256),
>>C = random:uniform(256),
>>D = random:uniform(256),
>>
>><<Float:32/signed-float>> = <<A, B, C, D>>.
>>
>>(depending on the values of A,B,C,D ; this can result in a badmatch).
>
>This is probably bit-combinations meaning "Infinity" and "NaN". It 
>would be nice if this operation didn't fail but instead returned the 
>above. (Is this possible and/or is it a performance penalty for this 
>?)

You are right; you can construct invalid floating-point bit patterns
with this method, and since Erlang doesn't include "not-a-numbers" in
the float data type, an exit is signalled. If you expect there to be
non-numbers in the binary, you can use 'catch' to catch the exit:

bytes_to_float(A,B,C,D) ->
    <<Float:32/signed-float>> = <<A, B, C, D>>,
    Float.

convert(A,B,C,D) ->
    case catch bytes_to_float(A,B,C,D) of
	{'EXIT', _} ->
	    not_a_number;
	F ->
	    F
    end.

>>
>>What kind of representation is used for floats (is this a local issue) ?

The representation is the IEEE 754 floating-point standard. This also
happens to be the native representation on the platforms on which the
commercial releases of Erlang runs.

Here is a description of the standard:
http://research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html

>>Also, is there any way to tell what precision that erlang uses ?

Internally, it uses the 'double' data type of C, which probably means
64 bits on most platforms.
-- 
Arndt Jonasson
arndt@REDACTED



More information about the erlang-questions mailing list