Why is 'Infinity' not allowed in Erlang

2020-06-13 20:13发布

问题:

Erlang (and by extension Elixir) supports floating-point numbers.

Some possible Floats:

  • 1.2345
  • 1.0e10
  • 1.0e-42

Erlang supports NaN (nan. in Erlang) (I am however yet to discover a method that outputs nan itself).

However, Erlang does not have support for Infinity. While common standards like IEEE-754 state that one should return Infinity when doing things like 1.0/0.0, instead, Erlang throws a bad arithmetic error.

The same happens when attempting to make floats that are 'too large' like 1.0e400.

There's probably some (historical?) reason behind this.

回答1:

Erlang does all sorts of "bad" things with floats (not quite IEEE 754 binary64): conflates -0 and +0 to 0, doesn't do +-SNaNs, +-QNaNs, +-denormals or +-infinity.

For actual, scientific computations with precise error handling, it's probably worth dropping into another language either with a Port, doing some RPC or writing C/C++ NIF.

Reference: http://steve.hollasch.net/cgindex/coding/ieeefloat.html

Update: I wrote a trivial ieee754 module here which classifies binary64 floats and converts those that Erlang supports.



回答2:

Looking in ./erts/emulator/sys/unix/sys_float.c

it appears to me that Erlang is using the underlying strtod implementation to convert to "standard" C floats.

On most unix systems, floating point was not implemented to that standard at the time Erlang was created, but values that would generate Infinity instead generate fpe signal errors.