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