|
| 1 | +fn to_prec(n: &BigInt) -> Precision { |
| 2 | + n.to_i32().unwrap_or(Precision::MAX) |
| 3 | +} |
| 4 | + |
| 5 | +fn erf_series(signal: &Option<Signal>, op: &Computable, p: Precision) -> BigInt { |
| 6 | + let rough_x = op.approx_signal(signal, -10); |
| 7 | + let x_sq_approx = (&rough_x * &rough_x) >> 20; |
| 8 | + |
| 9 | + let n_estimate = { |
| 10 | + let estimate = &x_sq_approx + BigInt::from(-p) + BigInt::from(10); |
| 11 | + if estimate < BigInt::one() { |
| 12 | + BigInt::one() |
| 13 | + } else { |
| 14 | + estimate |
| 15 | + } |
| 16 | + }; |
| 17 | + let magnitude_bits = to_prec(&((&x_sq_approx * BigInt::from(3)) / BigInt::from(2))) + 2; |
| 18 | + let guard_bits = (n_estimate.magnitude().bits() as Precision) + magnitude_bits + 4; |
| 19 | + let calc_precision = p - guard_bits; |
| 20 | + let op_prec = calc_precision - 8; |
| 21 | + let op_appr = op.approx_signal(signal, op_prec); |
| 22 | + let max_trunc_error = signed::ONE.deref() << (p - 4 - calc_precision); |
| 23 | + |
| 24 | + let mut n: i64 = 0; |
| 25 | + let mut current_term = scale(op_appr.clone(), op_prec - calc_precision); |
| 26 | + let mut current_sum = current_term.clone(); |
| 27 | + loop { |
| 28 | + if should_stop(signal) { |
| 29 | + break; |
| 30 | + } |
| 31 | + let prev = current_term; |
| 32 | + let mut t = scale(&prev * &op_appr, op_prec); |
| 33 | + t = scale(t * &op_appr, op_prec); |
| 34 | + t = (t * signed::TWO.deref()) / BigInt::from(2 * n + 3); |
| 35 | + n += 1; |
| 36 | + if t.is_zero() { |
| 37 | + break; |
| 38 | + } |
| 39 | + |
| 40 | + let prev_abs = prev.abs(); |
| 41 | + let cur_abs = t.abs(); |
| 42 | + if cur_abs < prev_abs { |
| 43 | + let denom = &prev_abs - &cur_abs; |
| 44 | + if &cur_abs * &prev_abs < &max_trunc_error * &denom { |
| 45 | + break; |
| 46 | + } |
| 47 | + } |
| 48 | + current_sum += &t; |
| 49 | + current_term = t; |
| 50 | + } |
| 51 | + scale(current_sum, calc_precision - p) |
| 52 | +} |
| 53 | + |
| 54 | +const NORMAL_QUANTILE_RESULT_MSD_BOUND: Precision = 5; |
| 55 | + |
| 56 | +fn normal_quantile( |
| 57 | + signal: &Option<Signal>, |
| 58 | + p: &Computable, |
| 59 | + seed: &BigInt, |
| 60 | + seed_prec: Precision, |
| 61 | + prec: Precision, |
| 62 | +) -> BigInt { |
| 63 | + if prec >= seed_prec || should_stop(signal) { |
| 64 | + return scale(seed.clone(), seed_prec - prec); |
| 65 | + } |
| 66 | + |
| 67 | + let appr_prec = (NORMAL_QUANTILE_RESULT_MSD_BOUND + prec) / 2 - 6; |
| 68 | + let xn_int = normal_quantile(signal, p, seed, seed_prec, appr_prec); |
| 69 | + let xn = Computable::integer(xn_int).shift_left(appr_prec); |
| 70 | + let fx = xn.clone().pnorm(); |
| 71 | + let phi_xn = xn.clone().dnorm(); |
| 72 | + let x_next = xn.add(fx.add(p.clone().negate()).multiply(phi_xn.inverse()).negate()); |
| 73 | + |
| 74 | + (x_next.approx_signal(signal, prec - 2) + signed::TWO.deref()) >> 2 |
| 75 | +} |
0 commit comments