| 1 | const std = @import("../std.zig"); |
| 2 | const math = std.math; |
| 3 | const expect = std.testing.expect; |
| 4 | |
| 5 | /// Returns whether x is a finite value. |
| 6 | pub fn isFinite(x: anytype) bool { |
| 7 | const T = @TypeOf(x); |
| 8 | const TBits = @Int(.unsigned, @typeInfo(T).float.bits); |
| 9 | const remove_sign = ~@as(TBits, 0) >> 1; |
| 10 | return @as(TBits, @bitCast(x)) & remove_sign < @as(TBits, @bitCast(math.inf(T))); |
| 11 | } |
| 12 | |
| 13 | test isFinite { |
| 14 | inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| { |
| 15 | // normals |
| 16 | try expect(isFinite(@as(T, 1.0))); |
| 17 | try expect(isFinite(-@as(T, 1.0))); |
| 18 | |
| 19 | // zero & subnormals |
| 20 | try expect(isFinite(@as(T, 0.0))); |
| 21 | try expect(isFinite(@as(T, -0.0))); |
| 22 | try expect(isFinite(math.floatTrueMin(T))); |
| 23 | |
| 24 | // other float limits |
| 25 | try expect(isFinite(math.floatMin(T))); |
| 26 | try expect(isFinite(math.floatMax(T))); |
| 27 | |
| 28 | // inf & nan |
| 29 | try expect(!isFinite(math.inf(T))); |
| 30 | try expect(!isFinite(-math.inf(T))); |
| 31 | try expect(!isFinite(math.nan(T))); |
| 32 | try expect(!isFinite(-math.nan(T))); |
| 33 | } |
| 34 | } |