Repository Public MIT
1#!/usr/bin/env python32# ORIX Calc3# File: Packages/ORIXStatistics/Reference/reflib.py4# Description: High-precision (mpmath) reference implementations of the special functions and helpers shared by the generators.5#6# Author: Simon-Pierre Boucher7# Contact: contact@spboucher.ai8import json, os, shutil9import mpmath as mp1011HERE = os.path.dirname(os.path.abspath(__file__))12OUT = os.path.join(HERE, "output")13TESTDATA = os.path.join(HERE, "..", "Tests", "ORIXStatisticsTests", "ReferenceData")14BASE_DPS = 5015mp.mp.dps = BASE_DPS161718def write(name, payload):19 """Writes Reference/output/<name>.json and mirrors it into the test bundle."""20 os.makedirs(OUT, exist_ok=True)21 os.makedirs(TESTDATA, exist_ok=True)22 path = os.path.join(OUT, name + ".json")23 with open(path, "w") as f:24 json.dump(payload, f, indent=0, sort_keys=True, allow_nan=False)25 f.write("\n")26 shutil.copyfile(path, os.path.join(TESTDATA, name + ".json"))27 n = len(payload["cases"]) if isinstance(payload, dict) and "cases" in payload else len(payload)28 print(f"{name}.json: {n} entries")293031def fl(v):32 """Correctly rounded double of an mpmath number."""33 return float(mp.mpf(v))343536def representable(v):37 v = abs(mp.mpf(v))38 return v == 0 or (v > mp.mpf("1e-300") and v < mp.mpf("1e300"))394041def _gamma_p_series(a, x):42 a, x = mp.mpf(a), mp.mpf(x)43 term = mp.mpf(1); s = mp.mpf(1); n = 044 tol = mp.mpf(10) ** (-(mp.mp.dps + 5))45 while True:46 n += 147 term *= x / (a + n)48 s += term49 if term < tol * s:50 break51 return mp.exp(a * mp.log(x) - x - mp.loggamma(a + 1)) * s525354def _gamma_q_cf(a, x):55 # Legendre continued fraction evaluated backwards with a generous fixed depth, doubled until stable.56 a, x = mp.mpf(a), mp.mpf(x)57 def ev(depth):58 f = mp.mpf(0)59 for i in range(depth, 0, -1):60 f = (-i * (i - a)) / (x + 2 * i + 1 - a + f)61 return 1 / (x + 1 - a + f)62 depth = 20063 prev = ev(depth)64 while True:65 depth *= 266 cur = ev(depth)67 if abs(cur - prev) <= abs(cur) * mp.mpf(10) ** (-(mp.mp.dps - 5)):68 break69 prev = cur70 return mp.exp(a * mp.log(x) - x - mp.loggamma(a)) * cur717273def gamma_pq(a, x):74 """(P(a,x), Q(a,x)) to ~40 significant digits each."""75 if x == 0:76 return mp.mpf(0), mp.mpf(1)77 old = mp.mp.dps78 try:79 if mp.mpf(x) < mp.mpf(a) + 1:80 p = _gamma_p_series(a, x)81 q = 1 - p82 if q < mp.mpf("1e-8"):83 mp.mp.dps = old + 34084 q = 1 - _gamma_p_series(a, x)85 return +p, +q86 q = _gamma_q_cf(a, x)87 p = 1 - q88 if p < mp.mpf("1e-8"):89 mp.mp.dps = old + 34090 p = _gamma_p_series(a, x)91 return +p, +q92 finally:93 mp.mp.dps = old949596def log_beta(a, b):97 a, b = mp.mpf(a), mp.mpf(b)98 return mp.loggamma(a) + mp.loggamma(b) - mp.loggamma(a + b)99100101def _beta_series(a, b, x, y):102 # I_x(a,b) = x^a y^b / (a B(a,b)) * sum_n (a+b)_n/(a+1)_n x^n ; y = 1 - x given exactly.103 a, b, x, y = mp.mpf(a), mp.mpf(b), mp.mpf(x), mp.mpf(y)104 term = mp.mpf(1); s = mp.mpf(1); n = 0105 tol = mp.mpf(10) ** (-(mp.mp.dps + 5))106 while True:107 term *= (a + b + n) / (a + 1 + n) * x108 n += 1109 s += term110 if term < tol * s and n > 5:111 break112 if n > 400_000:113 raise RuntimeError("beta series too slow")114 return mp.exp(a * mp.log(x) + b * mp.log(y) - log_beta(a, b)) * s / a115116117def beta_pq(a, b, x, y=None):118 """(I_x(a,b), 1 - I_x(a,b)); pass y = 1 - x when x is close to 1."""119 x = mp.mpf(x)120 y = 1 - x if y is None else mp.mpf(y)121 if x <= 0:122 return mp.mpf(0), mp.mpf(1)123 if y <= 0:124 return mp.mpf(1), mp.mpf(0)125 old = mp.mp.dps126 try:127 if x < (mp.mpf(a) + 1) / (mp.mpf(a) + b + 2) and not (y < mp.mpf("5e-4") and mp.mpf(a) * y < 1e4):128 p = _beta_series(a, b, x, y)129 q = 1 - p130 if q < mp.mpf("1e-8"):131 mp.mp.dps = old + 340132 q = 1 - _beta_series(a, b, x, y)133 return +p, +q134 q = _beta_series(b, a, y, x)135 p = 1 - q136 if p < mp.mpf("1e-8"):137 mp.mp.dps = old + 340138 p = 1 - _beta_series(b, a, y, x)139 return +p, +q140 finally:141 mp.mp.dps = old142143144def ncdf(z):145 return mp.erfc(-mp.mpf(z) / mp.sqrt(2)) / 2146147148def nsf(z):149 return mp.erfc(mp.mpf(z) / mp.sqrt(2)) / 2150151152def solve(f, x0):153 """Root of f near x0 at working precision (secant from a double-precision start)."""154 x0 = mp.mpf(x0)155 h = abs(x0) * mp.mpf("1e-9") if x0 != 0 else mp.mpf("1e-12")156 return mp.findroot(f, (x0, x0 + h), solver="secant", tol=mp.mpf(10) ** (-35), maxsteps=200)157