master
1const std = @import("../std.zig");
2const math = std.math;
3const expect = std.testing.expect;
4
5/// Returns whether x is positive zero.
6pub inline fn isPositiveZero(x: anytype) bool {
7 const T = @TypeOf(x);
8 const bit_count = @typeInfo(T).float.bits;
9 const TBits = std.meta.Int(.unsigned, bit_count);
10 return @as(TBits, @bitCast(x)) == @as(TBits, 0);
11}
12
13/// Returns whether x is negative zero.
14pub inline fn isNegativeZero(x: anytype) bool {
15 const T = @TypeOf(x);
16 const bit_count = @typeInfo(T).float.bits;
17 const TBits = std.meta.Int(.unsigned, bit_count);
18 return @as(TBits, @bitCast(x)) == @as(TBits, 1) << (bit_count - 1);
19}
20
21test isPositiveZero {
22 inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
23 try expect(isPositiveZero(@as(T, 0.0)));
24 try expect(!isPositiveZero(@as(T, -0.0)));
25 try expect(!isPositiveZero(math.floatMin(T)));
26 try expect(!isPositiveZero(math.floatMax(T)));
27 try expect(!isPositiveZero(math.inf(T)));
28 try expect(!isPositiveZero(-math.inf(T)));
29 }
30}
31
32test isNegativeZero {
33 inline for ([_]type{ f16, f32, f64, f80, f128 }) |T| {
34 try expect(isNegativeZero(@as(T, -0.0)));
35 try expect(!isNegativeZero(@as(T, 0.0)));
36 try expect(!isNegativeZero(math.floatMin(T)));
37 try expect(!isNegativeZero(math.floatMax(T)));
38 try expect(!isNegativeZero(math.inf(T)));
39 try expect(!isNegativeZero(-math.inf(T)));
40 }
41}