vile / scheme / big_number.v
455 lines · 412 sloc · 16.35 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1module scheme
2
3import math
4import math.big
5import math.bits
6
7@[heap]
8struct BigInteger {
9 value big.Integer
10}
11
12@[heap]
13struct BigRational {
14 numerator big.Integer
15 denominator big.Integer
16}
17
18fn (value Value) big_integer_pointer() &BigInteger {
19 return unsafe { &BigInteger(value.pointer()) }
20}
21
22fn (value Value) big_rational_pointer() &BigRational {
23 return unsafe { &BigRational(value.pointer()) }
24}
25
26@[inline]
27fn is_big_exact(value Value) bool {
28 return value.tag in [.big_integer, .big_rational]
29}
30
31@[inline]
32fn is_exact_integer(value Value) bool {
33 return value.tag in [.integer, .big_integer]
34}
35
36// No byte array, formatting, or private limb access is needed to narrow a big
37// result. get_bit reads two's complement; the complement keeps signed casts in range.
38fn big_i64(value big.Integer) ?i64 {
39 if value.signum == 0 { return i64(0) }
40 width := value.bit_len()
41 if (value.signum > 0 && width > 63) || (value.signum < 0 && width > 64) { return none }
42 mut raw := u64(0)
43 for bit in 0 .. 64 { if value.get_bit(u32(bit)) { raw |= u64(1) << bit } }
44 if value.signum < 0 {
45 if raw >> 63 == 0 { return none }
46 return -1 - i64(~raw)
47 }
48 return i64(raw)
49}
50
51// Internal immutable results can retain shared limbs. Box their header once.
52fn owned_big_integer(value big.Integer) Value {
53 if small := big_i64(value) { return integer(small) }
54 return payload_value(.big_integer, &BigInteger{ value: value })
55}
56
57// integer_from_big snapshots the caller's limbs into the current allocator.
58// Like other host constructors, it must be called after popping a region when
59// the new value must outlive that region. Small results normalize inline.
60pub fn integer_from_big(value big.Integer) Value {
61 if small := big_i64(value) { return integer(small) }
62 return payload_value(.big_integer, &BigInteger{ value: value + big.zero_int })
63}
64
65// rational_from_big snapshots retained caller storage and normalizes the ratio.
66pub fn rational_from_big(numerator big.Integer, denominator big.Integer) !Value {
67 return normalize_big_rational(numerator, denominator, true)
68}
69
70// as_big_integer returns independent limbs in the currently active allocator.
71// Pop a host region before calling it to export a still-live Value from it.
72pub fn (value Value) as_big_integer() !big.Integer {
73 if value.tag == .integer { return big.integer_from_i64(value.whole()) }
74 if value.tag != .big_integer { return failure('expected an exact integer') }
75 return value.big_integer_pointer().value + big.zero_int
76}
77
78// as_big_rational returns independent numerator/denominator limbs. Integers
79// have denominator one, matching as_rational's existing numeric contract.
80pub fn (value Value) as_big_rational() !(big.Integer, big.Integer) {
81 match value.tag {
82 .integer { return big.integer_from_i64(value.whole()), big.integer_from_int(1) }
83 .rational {
84 r := value.rational_pointer()
85 return big.integer_from_i64(r.numerator), big.integer_from_i64(r.denominator)
86 }
87 .big_integer {
88 return value.big_integer_pointer().value + big.zero_int, big.integer_from_int(1)
89 }
90 .big_rational {
91 r := value.big_rational_pointer()
92 return r.numerator + big.zero_int, r.denominator + big.zero_int
93 }
94 else { return failure('expected an exact number') }
95 }
96}
97
98// Internal arithmetic borrows immutable headers, never clones a big input.
99fn big_integer_data(value Value) !big.Integer {
100 if value.tag == .integer { return big.integer_from_i64(value.whole()) }
101 if value.tag == .big_integer { return value.big_integer_pointer().value }
102 return failure('expected an exact integer')
103}
104
105fn big_exact_parts(value Value) !(big.Integer, big.Integer) {
106 match value.tag {
107 .integer { return big.integer_from_i64(value.whole()), big.one_int }
108 .big_integer { return value.big_integer_pointer().value, big.one_int }
109 .rational {
110 r := value.rational_pointer()
111 return big.integer_from_i64(r.numerator), big.integer_from_i64(r.denominator)
112 }
113 .big_rational {
114 r := value.big_rational_pointer()
115 return r.numerator, r.denominator
116 }
117 else { return failure('expected an exact number') }
118 }
119}
120
121fn exact_sign(value Value) int {
122 return match value.tag {
123 .integer {
124 if value.whole() < 0 {
125 -1
126 } else if value.whole() > 0 {
127 1
128 } else {
129 0
130 }
131 }
132 .rational {
133 if value.rational_pointer().numerator < 0 { -1 } else { 1 }
134 }
135 .big_integer { value.big_integer_pointer().value.signum }
136 .big_rational { value.big_rational_pointer().numerator.signum }
137 else { 0 }
138 }
139}
140
141fn big_quotient_exact(numerator big.Integer, divisor big.Integer) big.Integer {
142 return if divisor == big.one_int { numerator } else { numerator / divisor }
143}
144
145fn big_product(a big.Integer, b big.Integer) big.Integer {
146 if a == big.one_int { return b }
147 if b == big.one_int { return a }
148 return a * b
149}
150
151fn normalize_big_rational(numerator big.Integer, denominator big.Integer, copy bool) !Value {
152 if denominator.signum == 0 { return failure('division by zero') }
153 if numerator.signum == 0 { return integer(0) }
154 g := big_gcd(numerator, denominator)
155 return reduced_big_rational(big_quotient_exact(numerator, g), big_quotient_exact(denominator, g), copy && g == big.one_int)
156}
157
158// Arithmetic callers prove coprimality by cross-cancellation. A public
159// constructor copies only retained original limbs; reduced quotients own theirs.
160fn reduced_big_rational(numerator big.Integer, denominator big.Integer, copy bool) !Value {
161 if denominator.signum == 0 { return failure('division by zero') }
162 if numerator.signum == 0 { return integer(0) }
163 if denominator.signum < 0 {
164 return reduced_big_rational(big_neg_view(numerator), big_neg_view(denominator), copy)
165 }
166 if denominator == big.one_int {
167 return if copy { integer_from_big(numerator) } else { owned_big_integer(numerator) }
168 }
169 if n := big_i64(numerator) {
170 if d := big_i64(denominator) {
171 return payload_value(.rational, &Rational{ numerator: n, denominator: d })
172 }
173 }
174 return payload_value(.big_rational, &BigRational{
175 numerator: if copy {
176 numerator + big.zero_int
177 } else {
178 numerator
179 }
180 denominator: if copy { denominator + big.zero_int } else { denominator }
181 })
182}
183
184enum BigOperation {
185 add
186 subtract
187 multiply
188 divide
189}
190
191@[noinline]
192fn big_numeric_binary(a Value, b Value, operation BigOperation) !Value {
193 if b.tag == .integer && b.whole() == 0 {
194 if operation == .divide { return failure('division by zero') }
195 return if operation == .multiply { integer(0) } else { a }
196 }
197 if a.tag == .integer && a.whole() == 0 {
198 return match operation {
199 .add { b }
200 .subtract { numeric_negate(b)! }
201 else { integer(0) }
202 }
203 }
204 if b.tag == .integer && b.whole() == 1 && operation in [.multiply, .divide] { return a }
205 if a.tag == .integer && a.whole() == 1 && operation == .multiply { return b }
206 if b.tag == .integer && b.whole() == -1 && operation in [.multiply, .divide] {
207 return numeric_negate(a)
208 }
209 if a.tag == .integer && a.whole() == -1 && operation == .multiply { return numeric_negate(b) }
210 // Integer sums, differences and products need no rational reduction.
211 // Borrow immutable inputs; the existing operators own the result's limbs.
212 if operation != .divide && is_exact_integer(a) && is_exact_integer(b) {
213 x, y := big_integer_data(a)!, big_integer_data(b)!
214 if operation == .add { return owned_big_integer(x + y) }
215 if operation == .subtract { return owned_big_integer(x - y) }
216 return owned_big_integer(x * y)
217 }
218 an, ad := big_exact_parts(a)!
219 bn, bd := big_exact_parts(b)!
220 if operation in [.add, .subtract] {
221 g := big_gcd(ad, bd)
222 x := big_product(an, big_quotient_exact(bd, g))
223 y := big_product(bn, big_quotient_exact(ad, g))
224 n := if operation == .subtract { x - y } else { x + y }
225 if n.signum == 0 { return integer(0) }
226 h := big_gcd(n, g)
227 d := big_product(big_quotient_exact(ad, g), big_quotient_exact(bd, h))
228 return reduced_big_rational(big_quotient_exact(n, h), d, false)
229 }
230 if operation == .multiply {
231 g, h := big_gcd(an, bd), big_gcd(bn, ad)
232 return reduced_big_rational(big_product(big_quotient_exact(an, g), big_quotient_exact(bn, h)), big_product(big_quotient_exact(ad, h), big_quotient_exact(bd, g)), false)
233 }
234 if bn.signum == 0 { return failure('division by zero') }
235 g, h := big_gcd(an, bn), big_gcd(ad, bd)
236 return reduced_big_rational(big_product(big_quotient_exact(an, g), big_quotient_exact(bd, h)), big_product(big_quotient_exact(ad, h), big_quotient_exact(bn, g)), false)
237}
238
239fn big_numeric_negate(value Value) !Value {
240 n, d := big_exact_parts(value)!
241 return reduced_big_rational(big_neg_view(n), d, false)
242}
243
244fn big_compare(a big.Integer, b big.Integer) int {
245 return if a == b {
246 0
247 } else if a < b {
248 -1
249 } else {
250 1
251 }
252}
253
254fn big_exact_compare(a Value, b Value) !int {
255 // Canonical bignums lie strictly outside i64: comparing them with a small
256 // integer needs neither promoted operands nor a temporary limb array.
257 if a.tag == .big_integer && b.tag == .integer { return a.big_integer_pointer().value.signum }
258 if a.tag == .integer && b.tag == .big_integer { return -b.big_integer_pointer().value.signum }
259 an, ad := big_exact_parts(a)!
260 bn, bd := big_exact_parts(b)!
261 if an.signum != bn.signum { return if an.signum < bn.signum { -1 } else { 1 } }
262 if ad == bd { return big_compare(an, bn) }
263 return big_compare(big_product(an, bd), big_product(bn, ad))
264}
265
266fn big_compare_real(value Value, floating f64) !int {
267 if math.is_nan(floating) { return failure('cannot order NaN') }
268 if math.is_inf(floating, 0) { return if floating > 0 { -1 } else { 1 } }
269 return big_exact_compare(value, to_exact(real(floating))!)
270}
271
272// Bounded arithmetic signals overflow without constructing an error object.
273@[inline]
274fn small_add(a i64, b i64) ?i64 {
275 if (b > 0 && a > exact_max - b) || (b < 0 && a < exact_min - b) { return none }
276 return a + b
277}
278
279@[inline]
280fn small_subtract(a i64, b i64) ?i64 {
281 if (b > 0 && a < exact_min + b) || (b < 0 && a > exact_max + b) { return none }
282 return a - b
283}
284
285@[inline]
286fn small_multiply(a i64, b i64) ?i64 {
287 // The existing wide-product API detects overflow without signed division.
288 // magnitude handles exact_min without negating it in the signed domain.
289 high, low := bits.mul_64(magnitude(a), magnitude(b))
290 negative := (a < 0) != (b < 0)
291 limit := if negative { u64(1) << 63 } else { u64(exact_max) }
292 if high != 0 || low > limit { return none }
293 // Only a negative result can admit magnitude 2^63. Convert it explicitly
294 // rather than casting that unsigned magnitude or negating exact_min.
295 if low == u64(1) << 63 { return exact_min }
296 return if negative { -i64(low) } else { i64(low) }
297}
298
299@[inline]
300fn integer_add_value(a Value, b Value, subtract bool) !Value {
301 n := if subtract {
302 small_subtract(a.whole(), b.whole())
303 } else {
304 small_add(a.whole(), b.whole())
305 }
306 if value := n { return integer(value) }
307 return big_numeric_binary(a, b, if subtract { .subtract } else { .add })
308}
309
310@[inline]
311fn integer_multiply_value(a Value, b Value) !Value {
312 if value := small_multiply(a.whole(), b.whole()) { return integer(value) }
313 return big_numeric_binary(a, b, .multiply)
314}
315
316fn is_integer_number(value Value) bool {
317 return is_exact_integer(value) || (value.tag == .real && !math.is_inf(value.floating(), 0) && !math.is_nan(value.floating()) && math.floor(value.floating()) == value.floating())
318}
319
320fn big_integer_division(p Primitive, a Value, b Value) !Value {
321 if !is_integer_number(a) || !is_integer_number(b) { return failure('expected an integer') }
322 inexact := a.tag == .real || b.tag == .real
323 x, y := integer_value_big(a), integer_value_big(b)
324 if y.signum == 0 { return failure('division by zero') }
325 mut q, mut r := x.div_mod_checked(y)!
326 if p in [.floor_quotient, .floor_divide, .modulo] && r.signum != 0 && r.signum != y.signum {
327 q = q - big.one_int
328 r = r + y
329 }
330 if inexact {
331 if p in [.quotient, .floor_quotient] {
332 return inexact_integer_result(q, negative_number(a) != negative_number(b))
333 }
334 if p in [.remainder, .modulo] { return inexact_integer_result(r, negative_number(a)) }
335 return numeric_values(inexact_integer_result(q, negative_number(a) != negative_number(b))!, inexact_integer_result(r, negative_number(a))!)
336 }
337 if p in [.quotient, .floor_quotient] { return owned_big_integer(q) }
338 if p in [.remainder, .modulo] { return owned_big_integer(r) }
339 return numeric_values(owned_big_integer(q), owned_big_integer(r))
340}
341
342fn big_gcd_lcm(lcm bool, args []Value, inexact bool) !Value {
343 mut result := if lcm { big.one_int } else { big.zero_int }
344 for value in args {
345 operand := integer_value_big(value)
346 common := big_gcd(result, operand)
347 result = if lcm { big_product(big_quotient_exact(result, common), operand) } else { common }
348 if result.signum < 0 { result = big_neg_view(result) }
349 }
350 return if inexact { inexact_integer_result(result, false)! } else { owned_big_integer(result) }
351}
352
353fn big_rounded_number(p Primitive, value Value) !Value {
354 if value.tag == .big_integer { return value }
355 n, d := big_exact_parts(value)!
356 mut q, r := n.div_mod_checked(d)!
357 if p == .floor && r.signum < 0 { q = q - big.one_int }
358 if p == .ceiling && r.signum > 0 { q = q + big.one_int }
359 if p == .round && r.signum != 0 {
360 complement := if r.signum < 0 { d + r } else { d - r }
361 comparison := r.abs_cmp(complement)
362 if comparison > 0 || (comparison == 0 && q.is_odd()) {
363 q = if n.signum < 0 { q - big.one_int } else { q + big.one_int }
364 }
365 }
366 return owned_big_integer(q)
367}
368
369fn big_integer_root(value Value) !Value {
370 n := big_integer_data(value)!
371 if n.signum < 0 { return failure('exact-integer-sqrt requires a nonnegative exact integer') }
372 s := n.isqrt_checked()!
373 return numeric_values(owned_big_integer(s), owned_big_integer(n - s * s))
374}
375
376fn big_square_root(value Value) !Value {
377 n, d := big_exact_parts(value)!
378 nr, dr := n.isqrt_checked()!, d.isqrt_checked()!
379 if nr * nr == n && dr * dr == d { return reduced_big_rational(nr, dr, false) }
380 return real(math.sqrt(value.as_real()!))
381}
382
383fn big_float_exact(significand u64, exponent int, negative bool) !Value {
384 mut n := big.integer_from_u64(significand)
385 mut d := big.one_int
386 if exponent >= 0 { n = n.left_shift(u32(exponent)) } else { d = d.left_shift(u32(-exponent)) }
387 if negative { n = big_neg_view(n) }
388 return reduced_big_rational(n, d, false)
389}
390
391fn big_number_power(base Value, exponent Value) !Value {
392 power := exponent.big_integer_pointer().value
393 if base.tag == .real {
394 x := base.floating()
395 if x == 0 && power.signum < 0 { return failure('division by zero') }
396 if x == 1 { return real(1) }
397 if x == -1 { return real(if power.is_odd() { -1.0 } else { 1.0 }) }
398 if x == 0 { return real(signed_zero(math.f64_bits(x) >> 63 != 0 && power.is_odd())) }
399 return real(math.pow(x, exponent.as_real()!))
400 }
401 if numeric_compare(base, integer(0))! == 0 {
402 if power.signum < 0 { return failure('division by zero') }
403 return integer(0)
404 }
405 if numeric_compare(base, integer(1))! == 0 { return integer(1) }
406 if numeric_compare(base, integer(-1))! == 0 {
407 return integer(if power.is_odd() { -1 } else { 1 })
408 }
409 // Nontrivial powers beyond the signed-64-bit iteration range are an
410 // explicit computation limit. Do not truncate the exponent to pow's u32 API.
411 return failure('exact power exceeds supported computation range')
412}
413
414fn big_simplest_positive(lower Value, upper Value) !Value {
415 mut low, mut high := lower, upper
416 mut a, mut b, mut c, mut d := integer(1), integer(0), integer(0), integer(1)
417 for {
418 q := rounded_number(.floor, low)!
419 mut terminal := numeric_compare(low, q)! == 0
420 mut result := q
421 if !terminal && numeric_compare(q, rounded_number(.floor, high)!)! < 0 {
422 result = numeric_add(q, integer(1))!
423 terminal = true
424 }
425 if terminal {
426 return numeric_divide(numeric_add(numeric_multiply(a, result)!, b)!, numeric_add(numeric_multiply(c, result)!, d)!)
427 }
428 next_a := numeric_add(numeric_multiply(a, q)!, b)!
429 next_c := numeric_add(numeric_multiply(c, q)!, d)!
430 b, d = a, c
431 a, c = next_a, next_c
432 next_low := numeric_divide(integer(1), numeric_subtract(high, q)!)!
433 high = numeric_divide(integer(1), numeric_subtract(low, q)!)!
434 low = next_low
435 }
436 return unspecified()
437}
438
439// Public Integer value updates share its immutable backing storage without
440// reaching into private limbs. Only internal views use this; host exports copy.
441fn big_abs_view(value big.Integer) big.Integer {
442 return if value.signum < 0 { big.Integer{ ...value, signum: -value.signum } } else { value }
443}
444
445fn big_neg_view(value big.Integer) big.Integer {
446 return big.Integer{ ...value, signum: -value.signum }
447}
448
449fn big_gcd(a big.Integer, b big.Integer) big.Integer {
450 if a.signum == 0 { return big_abs_view(b) }
451 if b.signum == 0 { return big_abs_view(a) }
452 left, right := big_abs_view(a), big_abs_view(b)
453 if left == big.one_int || right == big.one_int { return big.one_int }
454 return left.gcd(right)
455}
456