-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbigint.rs
More file actions
499 lines (456 loc) · 15.4 KB
/
bigint.rs
File metadata and controls
499 lines (456 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! BigInt helper functions for RustPython.
//!
//! These functions handle cases where Python integers exceed i64 range.
//! They are not part of Python's math.integer module but are needed
//! for RustPython's internal implementation.
use super::integer::perm_comb_small;
#[cfg(feature = "malachite-bigint")]
pub(crate) use malachite_bigint::{BigInt, BigUint};
#[cfg(feature = "num-bigint")]
pub(crate) use num_bigint::{BigInt, BigUint};
use num_traits::{One, Signed, ToPrimitive};
// Perm/Comb for BigInt n
/// Compute perm(n, k) where n is a BigInt and k fits in u64.
/// Uses divide-and-conquer: P(n, k) = P(n, j) * P(n-j, k-j)
///
/// See: perm_comb in CPython mathmodule.c
pub fn perm_bigint(n: &BigInt, k: u64) -> BigUint {
if k == 0 {
return BigUint::one();
}
if k == 1 {
return n.magnitude().clone();
}
// P(n, k) = P(n, j) * P(n-j, k-j)
let j = k / 2;
let a = perm_bigint(n, j);
let n_minus_j = n - BigInt::from(j);
let b = perm_bigint(&n_minus_j, k - j);
a * b
}
/// Compute comb(n, k) where n is a BigInt and k fits in u64.
/// Uses divide-and-conquer: C(n, k) = C(n, j) * C(n-j, k-j) / C(k, j)
///
/// See: perm_comb in CPython mathmodule.c
pub fn comb_bigint(n: &BigInt, k: u64) -> BigUint {
if k == 0 {
return BigUint::one();
}
if k == 1 {
return n.magnitude().clone();
}
// C(n, k) = C(n, j) * C(n-j, k-j) / C(k, j)
let j = k / 2;
let a = comb_bigint(n, j);
let n_minus_j = n - BigInt::from(j);
let b = comb_bigint(&n_minus_j, k - j);
let numerator = a * b;
// C(k, j) using small version since k fits in u64
let divisor = perm_comb_small(k, j, true);
numerator / divisor
}
// Logarithm functions for BigInt
/// Compute frexp-like decomposition for BigInt.
/// Returns (mantissa, exponent) where:
/// - mantissa is in [0.5, 1.0) for positive n
/// - n ~= mantissa * 2^exponent
///
/// See: _PyLong_Frexp in CPython longobject.c
fn frexp_bigint(n: &BigInt) -> (f64, i64) {
let bits = n.bits();
if bits == 0 {
return (0.0, 0);
}
let bits = bits as i64;
// For small integers that fit in f64 mantissa (53 bits)
if bits <= 53 {
let x = n.to_f64().unwrap();
// frexp returns (m, e) where x = m * 2^e and 0.5 <= |m| < 1
let mut e: i32 = 0;
let m = crate::m::frexp(x, &mut e);
return (m, e as i64);
}
// For large integers, extract top ~53 bits
// Shift right to keep DBL_MANT_DIG + 2 = 55 bits for rounding
let shift = bits - 55;
let mantissa_int = n >> shift as u64;
let mut x = mantissa_int.to_f64().unwrap();
// x is now approximately n / 2^shift, with ~55 bits of precision
// Scale to [0.5, 1.0) range
// x is in [2^54, 2^55), so divide by 2^55 to get [0.5, 1.0)
x /= (1u64 << 55) as f64;
// Adjust if rounding pushed us to 1.0
if x == 1.0 {
x = 0.5;
return (x, bits + 1);
}
(x, bits)
}
/// Return the natural logarithm of a BigInt.
///
/// Returns Err(EDOM) if n is not positive.
pub fn log_bigint(n: &BigInt, base: Option<f64>) -> crate::Result<f64> {
if !n.is_positive() {
return Err(crate::Error::EDOM);
}
// Try direct conversion first
if let Some(x) = n.to_f64()
&& x.is_finite()
{
return super::log(x, base);
}
// Use frexp decomposition for large values
// n ~= x * 2^e, so log(n) = log(x) + log(2) * e
let (x, e) = frexp_bigint(n);
let log_n = crate::m::log(x) + std::f64::consts::LN_2 * (e as f64);
match base {
None => Ok(log_n),
Some(b) => {
if b <= 0.0 || b == 1.0 {
return Err(crate::Error::EDOM);
}
Ok(log_n / crate::m::log(b))
}
}
}
/// Return the base-2 logarithm of a BigInt.
///
/// Returns Err(EDOM) if n is not positive.
pub fn log2_bigint(n: &BigInt) -> crate::Result<f64> {
if !n.is_positive() {
return Err(crate::Error::EDOM);
}
// Try direct conversion first
if let Some(x) = n.to_f64()
&& x.is_finite()
{
return super::log2(x);
}
// Use frexp decomposition for large values
// n ~= x * 2^e, so log2(n) = log2(x) + e
let (x, e) = frexp_bigint(n);
Ok(crate::m::log2(x) + (e as f64))
}
/// Return the base-10 logarithm of a BigInt.
///
/// Returns Err(EDOM) if n is not positive.
pub fn log10_bigint(n: &BigInt) -> crate::Result<f64> {
if !n.is_positive() {
return Err(crate::Error::EDOM);
}
// Try direct conversion first
if let Some(x) = n.to_f64()
&& x.is_finite()
{
return super::log10(x);
}
// Use frexp decomposition for large values
// n ~= x * 2^e, so log10(n) = log10(x) + log10(2) * e
let (x, e) = frexp_bigint(n);
Ok(crate::m::log10(x) + std::f64::consts::LOG10_2 * (e as f64))
}
/// Compute ldexp(x, exp) where exp is a BigInt.
///
/// Returns x * 2^exp, handling BigInt exponent overflow:
/// - If x is 0, inf, or nan, returns x unchanged
/// - If exp overflows i32 positively, returns ERANGE (overflow)
/// - If exp overflows i32 negatively, returns signed zero (underflow)
pub fn ldexp_bigint(x: f64, exp: &BigInt) -> crate::Result<f64> {
// Special values are returned unchanged regardless of exponent
if x == 0.0 || !x.is_finite() {
return Ok(x);
}
// Fast path: try i64 first (like CPython's PyLong_AsLongAndOverflow)
let exp_clamped: i64 = match exp.try_into() {
Ok(e) => e,
Err(_) => {
// Exponent overflows i64, clamp to i64::MIN/MAX
if exp.is_negative() {
i64::MIN
} else {
i64::MAX
}
}
};
// Check against i32 bounds
if exp_clamped > i32::MAX as i64 {
// overflow
Err(crate::Error::ERANGE)
} else if exp_clamped < i32::MIN as i64 {
// underflow to signed zero
Ok(if x.is_sign_negative() { -0.0 } else { 0.0 })
} else {
super::ldexp(x, exp_clamped as i32)
}
}
#[cfg(test)]
mod tests {
use super::*;
use pyo3::prelude::*;
fn test_log_bigint_impl(n: &BigInt, base: Option<f64>) {
let rs = log_bigint(n, base);
crate::test::with_py_math(|py, math| {
// Convert BigInt to Python int via string using builtins.int()
let n_str = n.to_string();
let builtins = pyo3::types::PyModule::import(py, "builtins").unwrap();
let py_n = builtins
.getattr("int")
.unwrap()
.call1((n_str.as_str(),))
.unwrap();
let py_result = match base {
Some(b) => math.getattr("log").unwrap().call1((py_n, b)),
None => math.getattr("log").unwrap().call1((py_n,)),
};
match py_result {
Ok(py_val) => {
let py_f: f64 = py_val.extract().unwrap();
let rs_f = rs.unwrap();
if py_f.is_nan() && rs_f.is_nan() {
return;
}
// Handle exact equality (e.g., log(1) = 0)
if py_f == rs_f {
return;
}
// Allow small relative error for large numbers
let rel_err = ((py_f - rs_f) / py_f).abs();
assert!(
rel_err < 1e-10,
"log_bigint({n}, {base:?}): py={py_f} vs rs={rs_f}, rel_err={rel_err}"
);
}
Err(_) => {
assert!(
rs.is_err(),
"log_bigint({n}, {base:?}): py raised error but rs={rs:?}"
);
}
}
});
}
fn test_log2_bigint_impl(n: &BigInt) {
let rs = log2_bigint(n);
crate::test::with_py_math(|py, math| {
let n_str = n.to_string();
let builtins = pyo3::types::PyModule::import(py, "builtins").unwrap();
let py_n = builtins
.getattr("int")
.unwrap()
.call1((n_str.as_str(),))
.unwrap();
let py_result = math.getattr("log2").unwrap().call1((py_n,));
match py_result {
Ok(py_val) => {
let py_f: f64 = py_val.extract().unwrap();
let rs_f = rs.unwrap();
if py_f.is_nan() && rs_f.is_nan() {
return;
}
if py_f == rs_f {
return;
}
let rel_err = ((py_f - rs_f) / py_f).abs();
assert!(
rel_err < 1e-10,
"log2_bigint({n}): py={py_f} vs rs={rs_f}, rel_err={rel_err}"
);
}
Err(_) => {
assert!(
rs.is_err(),
"log2_bigint({n}): py raised error but rs={rs:?}"
);
}
}
});
}
fn test_log10_bigint_impl(n: &BigInt) {
let rs = log10_bigint(n);
crate::test::with_py_math(|py, math| {
let n_str = n.to_string();
let builtins = pyo3::types::PyModule::import(py, "builtins").unwrap();
let py_n = builtins
.getattr("int")
.unwrap()
.call1((n_str.as_str(),))
.unwrap();
let py_result = math.getattr("log10").unwrap().call1((py_n,));
match py_result {
Ok(py_val) => {
let py_f: f64 = py_val.extract().unwrap();
let rs_f = rs.unwrap();
if py_f.is_nan() && rs_f.is_nan() {
return;
}
if py_f == rs_f {
return;
}
let rel_err = ((py_f - rs_f) / py_f).abs();
assert!(
rel_err < 1e-10,
"log10_bigint({n}): py={py_f} vs rs={rs_f}, rel_err={rel_err}"
);
}
Err(_) => {
assert!(
rs.is_err(),
"log10_bigint({n}): py raised error but rs={rs:?}"
);
}
}
});
}
#[test]
fn edgetest_log_bigint() {
// Small values
for i in -10i64..=100 {
let n = BigInt::from(i);
test_log_bigint_impl(&n, None);
test_log_bigint_impl(&n, Some(2.0));
test_log_bigint_impl(&n, Some(10.0));
}
// Powers of 2 (important for log2)
for exp in 0..100u32 {
let n = BigInt::from(1u64) << exp;
test_log_bigint_impl(&n, None);
test_log_bigint_impl(&n, Some(2.0));
}
// Large values
let ten = BigInt::from(10);
for exp in [100, 200, 500, 1000] {
let n = ten.pow(exp);
test_log_bigint_impl(&n, None);
test_log_bigint_impl(&n, Some(2.0));
test_log_bigint_impl(&n, Some(10.0));
}
}
#[test]
fn edgetest_log2_bigint() {
for i in -10i64..=100 {
test_log2_bigint_impl(&BigInt::from(i));
}
for exp in 0..100u32 {
test_log2_bigint_impl(&(BigInt::from(1u64) << exp));
}
let ten = BigInt::from(10);
for exp in [100, 200, 500, 1000] {
test_log2_bigint_impl(&ten.pow(exp));
}
}
#[test]
fn edgetest_log10_bigint() {
for i in -10i64..=100 {
test_log10_bigint_impl(&BigInt::from(i));
}
let ten = BigInt::from(10);
for exp in [10, 50, 100, 200, 500, 1000] {
test_log10_bigint_impl(&ten.pow(exp));
}
}
proptest::proptest! {
#[test]
fn proptest_log_bigint(n in 1i64..1_000_000i64) {
test_log_bigint_impl(&BigInt::from(n), None);
}
#[test]
fn proptest_log_bigint_base2(n in 1i64..1_000_000i64) {
test_log_bigint_impl(&BigInt::from(n), Some(2.0));
}
#[test]
fn proptest_log_bigint_base10(n in 1i64..1_000_000i64) {
test_log_bigint_impl(&BigInt::from(n), Some(10.0));
}
#[test]
fn proptest_log2_bigint(n in 1i64..1_000_000i64) {
test_log2_bigint_impl(&BigInt::from(n));
}
#[test]
fn proptest_log10_bigint(n in 1i64..1_000_000i64) {
test_log10_bigint_impl(&BigInt::from(n));
}
}
// ldexp_bigint tests
fn test_ldexp_bigint_impl(x: f64, exp: &BigInt) {
let rs = ldexp_bigint(x, exp);
crate::test::with_py_math(|py, math| {
let exp_str = exp.to_string();
let builtins = pyo3::types::PyModule::import(py, "builtins").unwrap();
let py_exp = builtins
.getattr("int")
.unwrap()
.call1((exp_str.as_str(),))
.unwrap();
let py_result = math.getattr("ldexp").unwrap().call1((x, py_exp));
match py_result {
Ok(py_val) => {
let py_f: f64 = py_val.extract().unwrap();
let rs_f = rs.unwrap();
// Handle NaN
if py_f.is_nan() && rs_f.is_nan() {
return;
}
// Handle exact equality (including signed zeros and infinities)
if py_f == rs_f && py_f.is_sign_positive() == rs_f.is_sign_positive() {
return;
}
// Handle infinities
if py_f.is_infinite() && rs_f.is_infinite() {
assert_eq!(
py_f.is_sign_positive(),
rs_f.is_sign_positive(),
"ldexp_bigint({x}, {exp}): sign mismatch py={py_f} vs rs={rs_f}"
);
return;
}
panic!("ldexp_bigint({x}, {exp}): py={py_f} vs rs={rs_f}");
}
Err(_) => {
assert!(
rs.is_err(),
"ldexp_bigint({x}, {exp}): py raised error but rs={rs:?}"
);
}
}
});
}
#[test]
fn edgetest_ldexp_bigint() {
let x_vals = [
0.0,
-0.0,
1.0,
-1.0,
0.5,
-0.5,
2.0,
-2.0,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NAN,
];
let exp_vals: Vec<BigInt> = vec![
BigInt::from(0),
BigInt::from(1),
BigInt::from(-1),
BigInt::from(10),
BigInt::from(-10),
BigInt::from(100),
BigInt::from(-100),
BigInt::from(1000),
BigInt::from(-1000),
BigInt::from(i32::MAX),
BigInt::from(i32::MIN),
// Overflow cases
BigInt::from(i32::MAX as i64 + 1),
BigInt::from(i32::MIN as i64 - 1),
BigInt::from(10).pow(20),
-BigInt::from(10).pow(20),
];
for &x in &x_vals {
for exp in &exp_vals {
test_ldexp_bigint_impl(x, exp);
}
}
}
}