| 1 | const std = @import("../std.zig"); |
| 2 | const math = std.math; |
| 3 | const expect = std.testing.expect; |
| 4 | |
| 5 | /// Returns whether x is neither zero, subnormal, infinity, or NaN. |
| 6 | pub fn isNormal(x: anytype) bool { |
| 7 | const T = @TypeOf(x); |
| 8 | const TBits = @Int(.unsigned, @typeInfo(T).float.bits); |
| 9 | |
| 10 | const increment_exp = 1 << math.floatMantissaBits(T); |
| 11 | const remove_sign = ~@as(TBits, 0) >> 1; |
| 12 | |
| 13 | // We add 1 to the exponent, and if it overflows to 0 or becomes 1, |
| 14 | // then it was all zeroes (subnormal) or all ones (special, inf/nan). |
| 15 | // The sign bit is removed because all ones would overflow into it. |
| 16 | // For f80, even though it has an explicit integer part stored, |
| 17 | // the exponent effectively takes priority if mismatching. |
| 18 | const value = @as(TBits, @bitCast(x)) +% increment_exp; |
| 19 | return value & remove_sign >= (increment_exp << 1); |
| 20 | } |
| 21 | |
| 22 | test isNormal { |
| 23 | // TODO add `c_longdouble' when math.inf(T) supports it |
| 24 | inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| { |
| 25 | const TBits = @Int(.unsigned, @bitSizeOf(T)); |
| 26 | |
| 27 | // normals |
| 28 | try expect(isNormal(@as(T, 1.0))); |
| 29 | try expect(isNormal(math.floatMin(T))); |
| 30 | try expect(isNormal(math.floatMax(T))); |
| 31 | |
| 32 | // subnormals |
| 33 | try expect(!isNormal(@as(T, -0.0))); |
| 34 | try expect(!isNormal(@as(T, 0.0))); |
| 35 | try expect(!isNormal(@as(T, math.floatTrueMin(T)))); |
| 36 | |
| 37 | // largest subnormal |
| 38 | try expect(!isNormal(@as(T, @bitCast(~(~@as(TBits, 0) << math.floatFractionalBits(T)))))); |
| 39 | |
| 40 | // non-finite numbers |
| 41 | try expect(!isNormal(-math.inf(T))); |
| 42 | try expect(!isNormal(math.inf(T))); |
| 43 | try expect(!isNormal(math.nan(T))); |
| 44 | |
| 45 | // overflow edge-case (described in implementation, also see #10133) |
| 46 | try expect(!isNormal(@as(T, @bitCast(~@as(TBits, 0))))); |
| 47 | } |
| 48 | } |