Library for safe, fallible casting between different numerical types

Hello

I am working in a project with a lot of numbers being converted back and forth, a lot of it between f32 and i32 and back. (and i16, for good measure). I cannot find a safe fallible function I the standard library, as std.math.cast only works between in types. I have been using lossyCast, but looking at the code does not inspire trust in its safety.

int → float casts are lossless unless you’re dealing with very large numbers (or very small floats), in that case you could check whether

@abs(x) <= (1 << std.math.floatMantissaBits(f32)) - 1

which would mean that x is in the range of densely representable integers of f32. If that’s the case @floatFromInt is always lossless.

To put a limit on how much precision you want to lose on a float → int cast you could perform an f32i32f32 roundtrip with std.math.lossyCast and @floatFromInt and compare the lhs and rhs float with std.math.approxEqAbs/std.math.approxEqRel (and then fail if they’re too far apart).

4 Likes