master
1const std = @import("../std.zig");
2const builtin = @import("builtin");
3const math = std.math;
4const meta = std.meta;
5const expect = std.testing.expect;
6
7pub fn isNan(x: anytype) bool {
8 return x != x;
9}
10
11/// TODO: LLVM is known to miscompile on some architectures to quiet NaN -
12/// this is tracked by https://github.com/ziglang/zig/issues/14366
13pub fn isSignalNan(x: anytype) bool {
14 const T = @TypeOf(x);
15 const U = meta.Int(.unsigned, @bitSizeOf(T));
16 const quiet_signal_bit_mask = 1 << (math.floatFractionalBits(T) - 1);
17 return isNan(x) and (@as(U, @bitCast(x)) & quiet_signal_bit_mask == 0);
18}
19
20test isNan {
21 inline for ([_]type{ f16, f32, f64, f80, f128, c_longdouble }) |T| {
22 try expect(isNan(math.nan(T)));
23 try expect(isNan(-math.nan(T)));
24 try expect(isNan(math.snan(T)));
25 try expect(!isNan(@as(T, 1.0)));
26 try expect(!isNan(@as(T, math.inf(T))));
27 }
28}
29
30test isSignalNan {
31 if (builtin.zig_backend == .stage2_x86_64 and builtin.object_format == .coff and builtin.abi != .gnu) return error.SkipZigTest;
32
33 inline for ([_]type{ f16, f32, f64, f80, f128, c_longdouble }) |T| {
34 // TODO: Signalling NaN values get converted to quiet NaN values in
35 // some cases where they shouldn't such that this can fail.
36 // See https://github.com/ziglang/zig/issues/14366
37 if (!builtin.cpu.arch.isArm() and
38 !builtin.cpu.arch.isAARCH64() and
39 builtin.cpu.arch != .hexagon and
40 !builtin.cpu.arch.isMIPS32() and
41 !builtin.cpu.arch.isPowerPC() and
42 builtin.zig_backend != .stage2_c)
43 {
44 try expect(isSignalNan(math.snan(T)));
45 }
46 try expect(!isSignalNan(math.nan(T)));
47 try expect(!isSignalNan(@as(T, 1.0)));
48 try expect(!isSignalNan(math.inf(T)));
49 }
50}