Round an Elixir float to 32 bits

Elixir floats are always 64-bit. But if a NIF or GPU buffer later stores them as 32-bit floats, two different Elixir values may become equal:

611.99999 < 612.0
#=> true

611.99999 and 612.0 are different in Elixir, but as 32-bit floats they are the same bytes:

<<611.99999::float-32>>
#=> <<68, 25, 0, 0>>

<<612.0::float-32>>
#=> <<68, 25, 0, 0>>

To check what the other side would actually get, round the values to 32 bits before comparing. You can do it without any library with a bitstring round trip:

defp f32(value) do
  <<rounded::float-32>> = <<value::float-32>>
  rounded
end

Then compare:

def ensure_below!(value, upper_bound) do
  if f32(value) >= f32(upper_bound) do
    raise ArgumentError, "value #{value} doesn't fit under #{upper_bound} as a 32-bit float"
  end

  value
end

ensure_below!(611.99999, 612.0)
#=> ** (ArgumentError) value 611.99999 doesn't fit under 612.0 as a 32-bit float

This doesn’t check the range and the values that are too big don’t round. <<1.0e39::float-32>> encodes as the bit pattern for infinity, and matching it back fails with a MatchError (Elixir floats can’t be infinite). So we should check the range before rounding. The largest finite 32-bit float can be written down as its bit pattern.

The final version of the helper may look something like this:

<<f32_max::float-32>> = <<0x7F7FFFFF::32>>
@f32_max f32_max

defp f32(value) when abs(value) <= @f32_max do
  <<rounded::float-32>> = <<value::float-32>>
  rounded
end

defp f32(value) do
  raise ArgumentError, "#{value} is out of range for a 32-bit float"
end

def ensure_below!(value, upper_bound) do
  if f32(value) >= f32(upper_bound) do
    raise ArgumentError, "value #{value} doesn't fit under #{upper_bound} as a 32-bit float"
  end

  value
end

ensure_below!(1.0e39, 612.0)
#=> ** (ArgumentError) 1.0e39 is out of range for a 32-bit float
← All notes