fx_log2_test.nx source
↩ module page · 58 lines · 2055 B
1// fx_log2_test.nx -- KAT for the fixed-point binary logarithm.
2//
3// Run via the sovereign native lane:
4// _offc/nx_compile_x86_native.elf fx_log2_test.nx > t.s
5// as t.s -o t.o && ld -o t.elf t.o && ./t.elf ; echo $?
6// Exit 0 = all assertions PASS; exit N = assertion N failed.
7//
8// Goldens hand-computed; powers of two are EXACT, irrationals are
9// bounded (the fixed-point algorithm is deterministic, so the band is
10// a tight correctness window, not a fudge factor).
11
12import "fx.nx"
13
14// |a - b| <= tol
15func within(a: i64, b: i64, tol: i64) -> i64 {
16 var d: i64 = a - b
17 if d < 0 { d = 0 - d }
18 if d <= tol { return 1 }
19 return 0
20}
21
22func main() -> i64 {
23 // --- exact: log2(1) = 0 ---
24 if fx_log2(FX_ONE) != 0 { return 1 }
25
26 // --- exact powers of two: log2(2^k) = k * FX_ONE ---
27 if fx_log2(FX_ONE << 1) != FX_ONE { return 2 } // log2(2) = 1.0
28 if fx_log2(FX_ONE << 2) != (FX_ONE * 2) { return 3 } // log2(4) = 2.0
29 if fx_log2(FX_ONE << 3) != (FX_ONE * 3) { return 4 } // log2(8) = 3.0
30 if fx_log2(FX_ONE << 10) != (FX_ONE * 10) { return 5 } // log2(1024)=10.0
31
32 // --- exact below 1.0: log2(0.5) = -1.0 ---
33 if fx_log2(FX_HALF) != (0 - FX_ONE) { return 6 }
34
35 // --- irrational, bounded (log2(3) = 1.5849625... ; *65536 = 103872) ---
36 let l3: i64 = fx_log2(FX_ONE * 3)
37 if within(l3, 103872, 64) != 1 { return 7 }
38
39 // --- log2(6) = 2.5849625 ; *65536 = 169408 ---
40 let l6: i64 = fx_log2(FX_ONE * 6)
41 if within(l6, 169408, 64) != 1 { return 8 }
42
43 // --- log2(7) = 2.8073549 ; *65536 = 184017 ---
44 let l7: i64 = fx_log2(FX_ONE * 7)
45 if within(l7, 184017, 96) != 1 { return 9 }
46
47 // --- integer convenience wrapper agrees ---
48 if fx_log2_int(2) != FX_ONE { return 10 }
49 if fx_log2_int(4) != (FX_ONE * 2) { return 11 }
50
51 // --- DCG discount sanity: 1/log2(2) = 1.0 exactly ---
52 if fx_div(FX_ONE, fx_log2_int(2)) != FX_ONE { return 12 }
53
54 // --- domain guard: log2(0) returns 0, no crash ---
55 if fx_log2(0) != 0 { return 13 }
56
57 return 0
58}