code wiki / (root) / nx_complex.nx

nx_complex.nx source

↩ module page · 95 lines · 2479 B

1// nx_complex.nx -- complex numbers (a + bi). 2// 3// Substrate-level complex arithmetic for theorems that need C. 4// Components stored as i64 (or PPB-scaled for fractional). Real and 5// imaginary parts independently. 6// 7// genealogy_id: cardano_1545 + bombelli_1572 + euler_1777 + hamilton_complex_form 8// lineage_id: algebra_distributivity + commutativity + i_squared_minus_one 9// axioms: NX_AX_ALG_DISTRIBUTIVITY, NX_AX_ALG_COMMUTATIVITY 10 11// nx_safety_envelope: 12// intended_use: AUTO_APPLIED -- primitive-specific tuning queued 13// sil_target: SIL1 14// evidence: [bulk_applied_2026-05-16, see-file-comment-for-detail] 15// verdict: NOT_YET_EVALUATED 16 17import "syscalls.nx" 18import "nx_axioms.nx" 19import "nx_i128.nx" 20 21struct Complex { 22 re: i64, 23 im: i64, 24} 25 26const NX_COMPLEX_BYTES: i64 = 16 27 28func nx_cx_alloc() -> *Complex { 29 let raw: *u8 = sys_mmap(NX_COMPLEX_BYTES) 30 let c: *Complex = raw as *Complex 31 c.re = 0 32 c.im = 0 33 return c 34} 35 36func nx_cx_set(c: *Complex, re: i64, im: i64) -> i64 { 37 c.re = re 38 c.im = im 39 return 0 40} 41 42// (a + bi) + (c + di) = (a+c) + (b+d)i 43func nx_cx_add(a: *Complex, b: *Complex, out: *Complex) -> i64 { 44 out.re = a.re + b.re 45 out.im = a.im + b.im 46 return 0 47} 48 49// (a + bi) - (c + di) = (a-c) + (b-d)i 50func nx_cx_sub(a: *Complex, b: *Complex, out: *Complex) -> i64 { 51 out.re = a.re - b.re 52 out.im = a.im - b.im 53 return 0 54} 55 56// (a + bi) * (c + di) = (ac - bd) + (ad + bc)i 57func nx_cx_mul(a: *Complex, b: *Complex, out: *Complex) -> i64 { 58 out.re = nx_muldiv_i64(a.re, b.re, 1) - nx_muldiv_i64(a.im, b.im, 1) 59 out.im = nx_muldiv_i64(a.re, b.im, 1) + nx_muldiv_i64(a.im, b.re, 1) 60 return 0 61} 62 63// (a + bi)* = a - bi 64func nx_cx_conj(a: *Complex, out: *Complex) -> i64 { 65 out.re = a.re 66 out.im = -a.im 67 return 0 68} 69 70// |a + bi|^2 = a^2 + b^2 71func nx_cx_norm_sq(a: *Complex) -> i64 { 72 return nx_muldiv_i64(a.re, a.re, 1) + nx_muldiv_i64(a.im, a.im, 1) 73} 74 75// Equality test 76func nx_cx_eq(a: *Complex, b: *Complex) -> i64 { 77 if a.re != b.re { return 0 } 78 if a.im != b.im { return 0 } 79 return 1 80} 81 82// Powers via repeated multiplication. Returns a^n in out. 83func nx_cx_pow(a: *Complex, n: i64, out: *Complex) -> i64 { 84 out.re = 1 85 out.im = 0 86 var i: i64 = 0 87 let tmp: *Complex = nx_cx_alloc() 88 while i < n { 89 nx_cx_mul(out, a, tmp) 90 out.re = tmp.re 91 out.im = tmp.im 92 i = i + 1 93 } 94 return 0 95}