Skip to content

Commit 7279816

Browse files
authored
fix(core): gf16_from_f32(NaN) returns NaN instead of +inf (#45)
fromF32 collapsed NaN into infinity because the non-finite branch set mant=0 (the infinity encoding) without checking isNan first. Split into separate isNan and isInf checks; NaN now encodes as exp=0x3F, mant=1 (canonical GF16_NAN = 0x7E01). Add C-ABI test for NaN preservation round-trip. Closes #38
1 parent 04b50cc commit 7279816

2 files changed

Lines changed: 9 additions & 1 deletion

File tree

src/c_abi.zig

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,10 @@ test "C-ABI: gf16_is_nan and gf16_is_inf" {
285285

286286
const zero = gf16_from_f32(0.0);
287287
try std.testing.expect(gf16_is_zero(zero));
288+
289+
const nan_val = gf16_from_f32(std.math.nan(f32));
290+
try std.testing.expect(gf16_is_nan(nan_val));
291+
try std.testing.expect(!gf16_is_inf(nan_val));
288292
}
289293

290294
test "C-ABI: gf16_phi_quantize" {

src/formats/golden_float16.zig

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,11 @@ pub const GF16 = packed struct(u16) {
8888
pub fn fromF32(v: f32) GF16 {
8989
if (v == 0.0) return .{ .mant = 0, .exp = 0, .sign = 0 };
9090

91-
if (!std.math.isFinite(v)) {
91+
if (std.math.isNan(v)) {
92+
return .{ .mant = 1, .exp = 0x3F, .sign = 0 };
93+
}
94+
95+
if (std.math.isInf(v)) {
9296
return .{ .mant = 0, .exp = 0x3F, .sign = @intFromBool(v < 0) };
9397
}
9498

0 commit comments

Comments
 (0)