rsarray 1.2.10__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. rsarray/__init__.py +12028 -0
  2. rsarray/_core/__init__.py +213 -0
  3. rsarray/_core/_exceptions.py +83 -0
  4. rsarray/_core/_internal.py +331 -0
  5. rsarray/_core/_multiarray_tests.py +129 -0
  6. rsarray/_core/_multiarray_umath.py +121 -0
  7. rsarray/_core/_rational_tests.py +52 -0
  8. rsarray/_core/arrayprint.py +36 -0
  9. rsarray/_core/fromnumeric.py +31 -0
  10. rsarray/_core/function_base.py +84 -0
  11. rsarray/_core/multiarray.py +385 -0
  12. rsarray/_core/numeric.py +28 -0
  13. rsarray/_core/numerictypes.py +233 -0
  14. rsarray/_core/records.py +14 -0
  15. rsarray/_core/shape_base.py +23 -0
  16. rsarray/_core/strings.py +78 -0
  17. rsarray/_core/umath.py +176 -0
  18. rsarray/_dtypes.py +1229 -0
  19. rsarray/_extra.py +6621 -0
  20. rsarray/_typing.py +24 -0
  21. rsarray/array_methods.py +1224 -0
  22. rsarray/array_ops.py +1585 -0
  23. rsarray/char.py +1590 -0
  24. rsarray/exceptions.py +45 -0
  25. rsarray/fft/__init__.py +231 -0
  26. rsarray/io.py +453 -0
  27. rsarray/lib/__init__.py +102 -0
  28. rsarray/lib/_function_base_impl.py +37 -0
  29. rsarray/lib/_index_tricks_impl.py +98 -0
  30. rsarray/lib/_nanfunctions_impl.py +1637 -0
  31. rsarray/lib/_stride_tricks_impl.py +110 -0
  32. rsarray/lib/recfunctions.py +1222 -0
  33. rsarray/lib/stride_tricks.py +106 -0
  34. rsarray/linalg/__init__.py +2603 -0
  35. rsarray/linalg/_linalg.py +91 -0
  36. rsarray/linalg/_pylinalg.py +1008 -0
  37. rsarray/linalg/lapack_lite.py +13 -0
  38. rsarray/ma/__init__.py +92 -0
  39. rsarray/ma/core.py +1385 -0
  40. rsarray/ma/extras.py +711 -0
  41. rsarray/ma/mrecords.py +144 -0
  42. rsarray/math_functions.py +965 -0
  43. rsarray/matlib.py +67 -0
  44. rsarray/num_core.cp313-win_amd64.pyd +0 -0
  45. rsarray/polynomial/__init__.py +148 -0
  46. rsarray/polynomial/_npcompat.py +721 -0
  47. rsarray/polynomial/polynomial.py +1082 -0
  48. rsarray/random/__init__.py +2266 -0
  49. rsarray/random/_distributions.py +773 -0
  50. rsarray/rec.py +207 -0
  51. rsarray/statistics.py +1360 -0
  52. rsarray/strings.py +349 -0
  53. rsarray/typing/__init__.py +26 -0
  54. rsarray-1.2.10.dist-info/METADATA +280 -0
  55. rsarray-1.2.10.dist-info/RECORD +59 -0
  56. rsarray-1.2.10.dist-info/WHEEL +4 -0
  57. rsarray-1.2.10.dist-info/licenses/LICENSE +21 -0
  58. rsarray-1.2.10.dist-info/licenses/NOTICE +7 -0
  59. rsarray-1.2.10.dist-info/sboms/rsarray.cyclonedx.json +2789 -0
@@ -0,0 +1,773 @@
1
+ # SPDX-License-Identifier: MIT
2
+ """纯 Python 分布采样器(legacy RandomState / 模块级函数补齐用)。
3
+
4
+ 设计:无状态。每个采样器由 ``next_u``(返回 [0,1) 均匀浮点)与
5
+ ``next_normal``(返回标准正态浮点)驱动,返回**单个 Python 标量**。
6
+ 数组参数广播 / size 前缀 / 结果封装由 ``random.__init__`` 的
7
+ ``_sample_dist`` 完成,本文件只负责单点采样的数学。
8
+
9
+ 边界语义以 2.5.4 为 oracle(逐条探测对齐):
10
+ * 参数为 ``-0.``(负零符号位)或负数 → ValueError;
11
+ * 参数为 ``+0`` → 返回 0(lognormal 为 exp(mean)=1),不报错。
12
+ 数值算法对齐 数组语义(逆变换 / Marsaglia-Tsang gamma /
13
+ 拒绝采样等),统计性质正确;但不追求与 逐位一致
14
+ (那需要 MT19937/PCG64 的 legacy 精确流,见 linalg 同级的独立任务)。
15
+ """
16
+
17
+ import math
18
+
19
+ # 2.5.4 RandomState()._poisson_lam_max 的 oracle 值
20
+ _POISSON_LAM_MAX = 9.223372006484771e+18
21
+
22
+ _ZETA_CACHE = {}
23
+
24
+
25
+ def _is_neg_zero(x):
26
+ return x == 0.0 and math.copysign(1.0, x) < 0.0
27
+
28
+
29
+ def _zeta(a):
30
+ """Riemann zeta(a),a>1(带缓存,尾部积分界截断)。"""
31
+ if a in _ZETA_CACHE:
32
+ return _ZETA_CACHE[a]
33
+ s = 0.0
34
+ k = 1
35
+ term = 1.0
36
+ while True:
37
+ term = k ** (-a)
38
+ s += term
39
+ # 尾部积分界:sum_{j>k} j^-a <= (k+1)^(1-a)/(a-1)
40
+ if term < 1e-15 * s:
41
+ break
42
+ k += 1
43
+ if k > 10 ** 7:
44
+ break
45
+ _ZETA_CACHE[a] = s
46
+ return s
47
+
48
+
49
+ def _loggam(x):
50
+ """random_loggam(SPECFUN 级数)。用于 poisson PTRS / 超几何 HRUA。"""
51
+ a = (8.333333333333333e-02, -2.777777777777778e-03,
52
+ 7.936507936507937e-04, -5.952380952380952e-04,
53
+ 8.417508417508418e-04, -1.917526917526918e-03,
54
+ 6.410256410256410e-03, -2.955065359477124e-02,
55
+ 1.796443723688307e-01, -1.39243221690590e+00)
56
+ if (x == 1.0) or (x == 2.0):
57
+ return 0.0
58
+ n = int(7 - x) if x < 7.0 else 0
59
+ x0 = x + n
60
+ x2 = (1.0 / x0) * (1.0 / x0)
61
+ lg2pi = 1.8378770664093453e+00
62
+ gl0 = a[9]
63
+ for k in range(8, -1, -1):
64
+ gl0 *= x2
65
+ gl0 += a[k]
66
+ gl = gl0 / x0 + 0.5 * lg2pi + (x0 - 0.5) * math.log(x0) - x0
67
+ if x < 7.0:
68
+ for _k in range(1, n + 1):
69
+ gl -= math.log(x0 - 1.0)
70
+ x0 -= 1.0
71
+ return gl
72
+
73
+
74
+ def _broadcast_shapes(a, b):
75
+ out = []
76
+ la, lb = list(reversed(a)), list(reversed(b))
77
+ for i in range(max(len(la), len(lb))):
78
+ da = la[i] if i < len(la) else 1
79
+ db = lb[i] if i < len(lb) else 1
80
+ if da == 1:
81
+ out.append(db)
82
+ elif db == 1:
83
+ out.append(da)
84
+ elif da == db:
85
+ out.append(da)
86
+ else:
87
+ raise ValueError(
88
+ "shape mismatch: cannot broadcast %s and %s" % (tuple(a), tuple(b)))
89
+ return tuple(reversed(out))
90
+
91
+
92
+ class Samplers:
93
+ """单点采样器集合。所有方法返回单个 Python 标量。"""
94
+
95
+ def __init__(self, next_u, next_normal):
96
+ self._u = next_u
97
+ self._n = next_normal
98
+ # binomial 缓存(binomial_t,跨调用持久)
99
+ self._bin_has = 0
100
+ self._bin_nsave = None
101
+ self._bin_psave = None
102
+ self._bin_q = 0.0
103
+ self._bin_r = 0.0
104
+ self._bin_c = 0.0
105
+ self._bin_m = 0
106
+ self._bin_fm = 0.0
107
+ self._bin_p1 = 0.0
108
+ self._bin_xm = 0.0
109
+ self._bin_xl = 0.0
110
+ self._bin_xr = 0.0
111
+ self._bin_laml = 0.0
112
+ self._bin_lamr = 0.0
113
+ self._bin_p2 = 0.0
114
+ self._bin_p3 = 0.0
115
+ self._bin_p4 = 0.0
116
+
117
+ # ------------------------------------------------------------------
118
+ # 连续分布
119
+ # ------------------------------------------------------------------
120
+ def standard_normal(self):
121
+ return self._n()
122
+
123
+ def normal(self, loc=0.0, scale=1.0):
124
+ if scale < 0.0 or _is_neg_zero(scale):
125
+ raise ValueError("scale < 0")
126
+ if scale == 0.0:
127
+ return float(loc)
128
+ return loc + scale * self._n()
129
+
130
+ def uniform(self, low=0.0, high=1.0):
131
+ if not (low < high):
132
+ raise ValueError("high <= low")
133
+ if not math.isfinite(high - low):
134
+ raise OverflowError("uniform range overflows float64")
135
+ return low + (high - low) * self._u()
136
+
137
+ def standard_exponential(self):
138
+ # legacy: -log(1-U),U in [0,1)
139
+ u = self._u()
140
+ return -math.log(1.0 - u)
141
+
142
+ def exponential(self, scale=1.0):
143
+ if scale < 0.0 or _is_neg_zero(scale):
144
+ raise ValueError("scale < 0")
145
+ if scale == 0.0:
146
+ return 0.0
147
+ return scale * self.standard_exponential()
148
+
149
+ def standard_gamma(self, shape):
150
+ if shape < 0.0 or _is_neg_zero(shape):
151
+ raise ValueError("shape < 0")
152
+ if shape == 0.0:
153
+ return 0.0
154
+ return self._gamma_mt(shape)
155
+
156
+ def gamma(self, shape, scale=1.0):
157
+ if shape < 0.0 or _is_neg_zero(shape):
158
+ raise ValueError("shape < 0")
159
+ if scale < 0.0 or _is_neg_zero(scale):
160
+ raise ValueError("scale < 0")
161
+ if shape == 0.0:
162
+ return 0.0
163
+ return scale * self._gamma_mt(shape)
164
+
165
+ def chisquare(self, df):
166
+ if df < 0.0 or _is_neg_zero(df):
167
+ raise ValueError("df < 0")
168
+ if df == 0.0:
169
+ return 0.0
170
+ return 2.0 * self._gamma_mt(df / 2.0)
171
+
172
+ def _gamma_mt(self, alpha):
173
+ """legacy standard_gamma:shape==1 走指数;shape<1 Ahrens-Dieter;
174
+ shape>=1 Marsaglia-Tsang(含 gauss 缓存)。"""
175
+ if alpha == 1.0:
176
+ return self.standard_exponential()
177
+ if alpha == 0.0:
178
+ return 0.0
179
+ if alpha < 1.0:
180
+ while True:
181
+ u = self._u()
182
+ v = self.standard_exponential()
183
+ if u <= 1.0 - alpha:
184
+ x = u ** (1.0 / alpha)
185
+ if x <= v:
186
+ return x
187
+ else:
188
+ y = -math.log((1.0 - u) / alpha)
189
+ x = (1.0 - alpha + alpha * y) ** (1.0 / alpha)
190
+ if x <= (v + y):
191
+ return x
192
+ b = alpha - 1.0 / 3.0
193
+ c = 1.0 / math.sqrt(9.0 * b)
194
+ while True:
195
+ while True:
196
+ x = self._n()
197
+ v = 1.0 + c * x
198
+ if v > 0.0:
199
+ break
200
+ v = v * v * v
201
+ u = self._u()
202
+ if u < 1.0 - 0.0331 * (x * x) * (x * x):
203
+ return b * v
204
+ if math.log(u) < 0.5 * x * x + b * (1.0 - v + math.log(v)):
205
+ return b * v
206
+
207
+ def standard_cauchy(self):
208
+ # legacy: gauss / gauss(比值,不是 tan 逆 CDF)
209
+ return self._n() / self._n()
210
+
211
+ def cauchy(self, loc=0.0, scale=1.0):
212
+ return loc + scale * self.standard_cauchy()
213
+
214
+ def gumbel(self, loc=0.0, scale=1.0):
215
+ if scale < 0.0 or _is_neg_zero(scale):
216
+ raise ValueError("scale < 0")
217
+ if scale == 0.0:
218
+ return float(loc)
219
+ u = self._u()
220
+ while u <= 0.0 or u >= 1.0:
221
+ u = self._u()
222
+ return loc - scale * math.log(-math.log1p(-u))
223
+
224
+ def laplace(self, loc=0.0, scale=1.0):
225
+ if scale < 0.0 or _is_neg_zero(scale):
226
+ raise ValueError("scale < 0")
227
+ if scale == 0.0:
228
+ return float(loc)
229
+ u = self._u()
230
+ if u < 0.5:
231
+ return loc + scale * math.log(2.0 * u)
232
+ return loc - scale * math.log(2.0 * (1.0 - u))
233
+
234
+ def logistic(self, loc=0.0, scale=1.0):
235
+ if scale < 0.0 or _is_neg_zero(scale):
236
+ raise ValueError("scale < 0")
237
+ if scale == 0.0:
238
+ return float(loc)
239
+ u = self._u()
240
+ while u <= 0.0 or u >= 1.0:
241
+ u = self._u()
242
+ return loc + scale * math.log(u / (1.0 - u))
243
+
244
+ def weibull(self, a):
245
+ if a < 0.0 or _is_neg_zero(a):
246
+ raise ValueError("a < 0")
247
+ if a == 0.0:
248
+ return 0.0
249
+ # legacy: pow(standard_exponential, 1/a)
250
+ return self.standard_exponential() ** (1.0 / a)
251
+
252
+ def power(self, a):
253
+ if not (a > 0.0):
254
+ raise ValueError("a <= 0")
255
+ # legacy: pow(1 - exp(-standard_exponential), 1/a)
256
+ return (1.0 - math.exp(-self.standard_exponential())) ** (1.0 / a)
257
+
258
+ def rayleigh(self, scale=1.0):
259
+ if scale < 0.0 or _is_neg_zero(scale):
260
+ raise ValueError("scale < 0")
261
+ if scale == 0.0:
262
+ return 0.0
263
+ u = self._u()
264
+ return scale * math.sqrt(-2.0 * math.log1p(-u))
265
+
266
+ def pareto(self, a):
267
+ if not (a > 0.0):
268
+ raise ValueError("a <= 0")
269
+ # legacy: exp(standard_exponential / a) - 1
270
+ return math.exp(self.standard_exponential() / a) - 1.0
271
+
272
+ # ------------------------------------------------------------------
273
+ # f / t / 非中心族(经 gamma/normal 组合)
274
+ # ------------------------------------------------------------------
275
+ def f(self, dfnum, dfden):
276
+ if not (dfnum > 0.0) or not (dfden > 0.0):
277
+ raise ValueError("dfnum/dfden must be > 0")
278
+ # legacy: (chi2(dfnum)*dfden) / (chi2(dfden)*dfnum)
279
+ return ((self.chisquare(dfnum) * dfden)
280
+ / (self.chisquare(dfden) * dfnum))
281
+
282
+ def standard_t(self, df):
283
+ if not (df > 0.0):
284
+ raise ValueError("df must be > 0")
285
+ # legacy: sqrt(df/2) * gauss / sqrt(gamma(df/2))
286
+ num = self._n()
287
+ denom = self._gamma_mt(df / 2.0)
288
+ return math.sqrt(df / 2.0) * num / math.sqrt(denom)
289
+
290
+ def t(self, df):
291
+ return self.standard_t(df)
292
+
293
+ def noncentral_chisquare(self, df, nc):
294
+ if not (df > 0.0) or not (nc >= 0.0):
295
+ raise ValueError("df must be > 0, nc >= 0")
296
+ if nc == 0:
297
+ return self.chisquare(df)
298
+ if 1 < df:
299
+ # legacy: chisquare 先生成,再 gauss
300
+ chi2 = self.chisquare(df - 1.0)
301
+ n = self._n() + math.sqrt(nc)
302
+ return chi2 + n * n
303
+ i = self.poisson(nc / 2.0)
304
+ return self.chisquare(df + 2.0 * i)
305
+
306
+ def noncentral_f(self, dfnum, dfden, nc):
307
+ if not (dfnum > 0.0) or not (dfden > 0.0):
308
+ raise ValueError("dfnum/dfden must be > 0")
309
+ # legacy: t / (chisquare(dfden)*dfnum)
310
+ t = self.noncentral_chisquare(dfnum, nc) * dfden
311
+ return t / (self.chisquare(dfden) * dfnum)
312
+
313
+ def beta(self, a, b):
314
+ if not (a > 0.0) or not (b > 0.0):
315
+ raise ValueError("a/b must be > 0")
316
+ if (a <= 1.0) and (b <= 1.0):
317
+ # legacy: Johnk's algorithm (a,b <= 1)
318
+ while True:
319
+ u = self._u()
320
+ v = self._u()
321
+ x = u ** (1.0 / a)
322
+ y = v ** (1.0 / b)
323
+ if (x + y) <= 1.0:
324
+ if (x + y) > 0:
325
+ return x / (x + y)
326
+ else:
327
+ logx = math.log(u) / a
328
+ logy = math.log(v) / b
329
+ logm = logx if logx > logy else logy
330
+ logx -= logm
331
+ logy -= logm
332
+ return math.exp(
333
+ logx - math.log(math.exp(logx) + math.exp(logy)))
334
+ ga = self._gamma_mt(a)
335
+ gb = self._gamma_mt(b)
336
+ s = ga + gb
337
+ if s == 0.0:
338
+ # 极小 shape 下两 gamma 均下溢为 0 → 避免 0/0 NaN
339
+ return 0.5
340
+ return ga / s
341
+
342
+ def lognormal(self, mean=0.0, sigma=1.0):
343
+ if sigma < 0.0 or _is_neg_zero(sigma):
344
+ raise ValueError("sigma < 0")
345
+ if sigma == 0.0:
346
+ return math.exp(mean)
347
+ return math.exp(self.normal(mean, sigma))
348
+
349
+ def triangular(self, left=0.0, mode=0.5, right=1.0):
350
+ if not (left < right):
351
+ raise ValueError("need left < right")
352
+ if not (left <= mode <= right):
353
+ raise ValueError("need left <= mode <= right")
354
+ u = self._u()
355
+ c = (mode - left) / (right - left)
356
+ if u < c:
357
+ return left + math.sqrt(u * (right - left) * (mode - left))
358
+ return right - math.sqrt((1.0 - u) * (right - left) * (right - mode))
359
+
360
+ def triangle(self, left=0.0, mode=0.5, right=1.0):
361
+ return self.triangular(left, mode, right)
362
+
363
+ def vonmises(self, mu, kappa):
364
+ # legacy_vonmises(legacy-distributions.c L646-702)逐位对齐。
365
+ # mu 在采样内部加入,随后 wrap 到 [-pi, pi](保号 fmod)。
366
+ if math.isnan(kappa):
367
+ return math.nan
368
+ if kappa < 1e-8:
369
+ # 特例:近均匀,不应用 mu/wrap
370
+ return math.pi * (2.0 * self._u() - 1.0)
371
+ if kappa < 1e-5:
372
+ # kappa=0 的二阶泰勒展开(double 精度下 rho 在 1.4e-8 前恒为 0)
373
+ s = 1.0 / kappa + kappa
374
+ else:
375
+ # 1e-5 <= kappa <= 1e6
376
+ r = 1.0 + math.sqrt(1.0 + 4.0 * kappa * kappa)
377
+ rho = (r - math.sqrt(2.0 * r)) / (2.0 * kappa)
378
+ s = (1.0 + rho * rho) / (2.0 * rho)
379
+ while True:
380
+ U = self._u()
381
+ Z = math.cos(math.pi * U)
382
+ W = (1.0 + s * Z) / (s + Z)
383
+ Y = kappa * (s - W)
384
+ V = self._u()
385
+ # Y>=0 恒接受、Y<0 恒拒绝(V==0.0 安全)
386
+ if (Y * (2.0 - Y) - V) >= 0.0 or (math.log(Y / V) + 1.0 - Y) >= 0.0:
387
+ break
388
+ U = self._u()
389
+ result = math.acos(W)
390
+ if U < 0.5:
391
+ result = -result
392
+ result += mu
393
+ neg = result < 0
394
+ mod = abs(result)
395
+ mod = math.fmod(mod + math.pi, 2.0 * math.pi) - math.pi
396
+ if neg:
397
+ mod = -mod
398
+ return mod
399
+
400
+ def wald(self, mean, scale):
401
+ """inverse Gaussian(legacy,Wichura 1977)。"""
402
+ if not (mean > 0.0) or not (scale > 0.0):
403
+ raise ValueError("mean/scale must be > 0")
404
+ mu_2l = mean / (2.0 * scale)
405
+ y = self._n()
406
+ y = mean * y * y
407
+ x = mean + mu_2l * (y - math.sqrt(4.0 * scale * y + y * y))
408
+ u = self._u()
409
+ if u <= mean / (mean + x):
410
+ return x
411
+ else:
412
+ return mean * mean / x
413
+
414
+ # ------------------------------------------------------------------
415
+ # 离散分布
416
+ # ------------------------------------------------------------------
417
+ def geometric(self, p):
418
+ if not (0.0 < p <= 1.0):
419
+ raise ValueError("p must be in (0, 1]")
420
+ if p >= 0.333333333333333333333333:
421
+ # random_geometric_search
422
+ x = 1
423
+ s = p
424
+ prod = p
425
+ q = 1.0 - p
426
+ u = self._u()
427
+ while u > s:
428
+ prod *= q
429
+ s += prod
430
+ x += 1
431
+ return x
432
+ # legacy_geometric_inversion
433
+ return int(math.ceil(math.log1p(-self._u()) / math.log(1.0 - p)))
434
+
435
+ def binomial(self, n, p):
436
+ n = int(n)
437
+ if n < 0:
438
+ raise ValueError("n must be >= 0")
439
+ if not (0.0 <= p <= 1.0) or _is_neg_zero(p):
440
+ raise ValueError("p must be in [0, 1]")
441
+ if n == 0 or p == 0.0:
442
+ # legacy 流语义:退化参数也消耗 1 个 double(gh-14522 回归测试固定)
443
+ self._u()
444
+ return 0
445
+ if p == 1.0:
446
+ self._u()
447
+ return n
448
+ # legacy: p<=0.5 用 p,否则对称用 q=1-p
449
+ if p <= 0.5:
450
+ if p * n <= 30.0:
451
+ return self._bin_inversion(n, p)
452
+ return self._bin_btpe(n, p)
453
+ q = 1.0 - p
454
+ if q * n <= 30.0:
455
+ return n - self._bin_inversion(n, q)
456
+ return n - self._bin_btpe(n, q)
457
+
458
+ def _bin_inversion(self, n, p):
459
+ # legacy_random_binomial_inversion(有状态缓存)
460
+ if (not self._bin_has) or (self._bin_nsave != n) \
461
+ or (self._bin_psave != p):
462
+ self._bin_nsave = n
463
+ self._bin_psave = p
464
+ self._bin_has = 1
465
+ self._bin_q = q = 1.0 - p
466
+ self._bin_r = qn = math.exp(n * math.log(q))
467
+ self._bin_c = np_ = n * p
468
+ self._bin_m = bound = min(n, int(np_ + 10.0 * math.sqrt(np_ * q + 1)))
469
+ else:
470
+ q = self._bin_q
471
+ qn = self._bin_r
472
+ np_ = self._bin_c
473
+ bound = self._bin_m
474
+ x = 0
475
+ px = qn
476
+ u = self._u()
477
+ while u > px:
478
+ x += 1
479
+ if x > bound:
480
+ x = 0
481
+ px = qn
482
+ u = self._u()
483
+ else:
484
+ u -= px
485
+ px = ((n - x + 1) * p * px) / (x * q)
486
+ return x
487
+
488
+ def _bin_btpe(self, n, p):
489
+ # legacy_random_binomial_btpe(有状态缓存;legacy 用 13680. 且末两项加号)
490
+ if (not self._bin_has) or (self._bin_nsave != n) \
491
+ or (self._bin_psave != p):
492
+ self._bin_nsave = n
493
+ self._bin_psave = p
494
+ self._bin_has = 1
495
+ self._bin_r = r = min(p, 1.0 - p)
496
+ self._bin_q = q = 1.0 - r
497
+ self._bin_fm = fm = n * r + r
498
+ self._bin_m = m = int(math.floor(fm))
499
+ self._bin_p1 = p1 = math.floor(2.195 * math.sqrt(n * r * q) - 4.6 * q) + 0.5
500
+ self._bin_xm = xm = m + 0.5
501
+ self._bin_xl = xl = xm - p1
502
+ self._bin_xr = xr = xm + p1
503
+ self._bin_c = c = 0.134 + 20.5 / (15.3 + m)
504
+ a = (fm - xl) / (fm - xl * r)
505
+ self._bin_laml = laml = a * (1.0 + a / 2.0)
506
+ a = (xr - fm) / (xr * q)
507
+ self._bin_lamr = lamr = a * (1.0 + a / 2.0)
508
+ self._bin_p2 = p2 = p1 * (1.0 + 2.0 * c)
509
+ self._bin_p3 = p3 = p2 + c / laml
510
+ self._bin_p4 = p4 = p3 + c / lamr
511
+ else:
512
+ r = self._bin_r
513
+ q = self._bin_q
514
+ fm = self._bin_fm
515
+ m = self._bin_m
516
+ p1 = self._bin_p1
517
+ xm = self._bin_xm
518
+ xl = self._bin_xl
519
+ xr = self._bin_xr
520
+ c = self._bin_c
521
+ laml = self._bin_laml
522
+ lamr = self._bin_lamr
523
+ p2 = self._bin_p2
524
+ p3 = self._bin_p3
525
+ p4 = self._bin_p4
526
+ while True:
527
+ # Step10
528
+ nrq = n * r * q
529
+ u = self._u() * p4
530
+ v = self._u()
531
+ if u <= p1:
532
+ y = int(math.floor(xm - p1 * v + u))
533
+ # Step60
534
+ if p > 0.5:
535
+ y = n - y
536
+ return y
537
+ # u > p1 → Step20
538
+ if u <= p2:
539
+ x = xl + (u - p1) / c
540
+ v = v * c + 1.0 - abs(m - x + 0.5) / p1
541
+ if v > 1.0:
542
+ continue # Step10
543
+ y = int(math.floor(x))
544
+ else:
545
+ # u > p2 → Step30
546
+ if u <= p3:
547
+ y = int(math.floor(xl + math.log(v) / laml))
548
+ if (y < 0) or (v == 0.0):
549
+ continue # Step10
550
+ v = v * (u - p2) * laml
551
+ else:
552
+ # u > p3 → Step40
553
+ y = int(math.floor(xr - math.log(v) / lamr))
554
+ if (y > n) or (v == 0.0):
555
+ continue # Step10
556
+ v = v * (u - p3) * lamr
557
+ # Step50
558
+ k = abs(y - m)
559
+ if (k > 20) and (k < (nrq / 2.0 - 1)):
560
+ # Step52
561
+ rho = (k / nrq) * ((k * (k / 3.0 + 0.625)
562
+ + 0.16666666666666666) / nrq + 0.5)
563
+ t = -k * k / (2 * nrq)
564
+ A = math.log(v)
565
+ if A < (t - rho):
566
+ if p > 0.5:
567
+ y = n - y
568
+ return y
569
+ if A > (t + rho):
570
+ continue # Step10
571
+ x1 = y + 1.0
572
+ f1 = m + 1.0
573
+ z = n + 1.0 - m
574
+ w = n - y + 1.0
575
+ x2 = x1 * x1
576
+ f2 = f1 * f1
577
+ z2 = z * z
578
+ w2 = w * w
579
+ if A > (xm * math.log(f1 / x1)
580
+ + (n - m + 0.5) * math.log(z / w)
581
+ + (y - m) * math.log(w * r / (x1 * q))
582
+ + (13680. - (462. - (132. - (99. - 140. / f2) / f2) / f2) / f2)
583
+ / f1 / 166320.
584
+ + (13680. - (462. - (132. - (99. - 140. / z2) / z2) / z2) / z2)
585
+ / z / 166320.
586
+ + (13680. - (462. - (132. - (99. - 140. / x2) / x2) / x2) / x2)
587
+ / x1 / 166320.
588
+ + (13680. - (462. - (132. - (99. - 140. / w2) / w2) / w2) / w2)
589
+ / w / 166320.):
590
+ continue # Step10
591
+ if p > 0.5:
592
+ y = n - y
593
+ return y
594
+ else:
595
+ s = r / q
596
+ a = s * (n + 1)
597
+ F = 1.0
598
+ if m < y:
599
+ for i in range(m + 1, y + 1):
600
+ F *= (a / i - s)
601
+ elif m > y:
602
+ for i in range(y + 1, m + 1):
603
+ F /= (a / i - s)
604
+ if v > F:
605
+ continue # Step10
606
+ if p > 0.5:
607
+ y = n - y
608
+ return y
609
+
610
+ def negative_binomial(self, n, p):
611
+ if n < 0:
612
+ raise ValueError("n must be >= 0")
613
+ if not (0.0 < p <= 1.0):
614
+ raise ValueError("p must be in (0, 1]")
615
+ # legacy: poisson(gamma(n, (1-p)/p))
616
+ y = self.gamma(n, (1.0 - p) / p)
617
+ return self.poisson(y)
618
+
619
+ def poisson(self, lam):
620
+ if not (0.0 <= lam <= _POISSON_LAM_MAX):
621
+ raise ValueError("lam out of range")
622
+ if lam == 0:
623
+ return 0
624
+ # legacy: lam>=10 用 PTRS,否则 Knuth 乘法
625
+ if lam >= 10:
626
+ return self._poisson_ptrs(lam)
627
+ enlam = math.exp(-lam)
628
+ x = 0
629
+ prod = 1.0
630
+ while True:
631
+ u = self._u()
632
+ prod *= u
633
+ if prod > enlam:
634
+ x += 1
635
+ else:
636
+ return x
637
+
638
+ def _poisson_ptrs(self, lam):
639
+ # random_poisson_ptrs(Hoermann transformed rejection)
640
+ slam = math.sqrt(lam)
641
+ loglam = math.log(lam)
642
+ b = 0.931 + 2.53 * slam
643
+ a = -0.059 + 0.02483 * b
644
+ invalpha = 1.1239 + 1.1328 / (b - 3.4)
645
+ vr = 0.9277 - 3.6224 / (b - 2)
646
+ while True:
647
+ u = self._u() - 0.5
648
+ v = self._u()
649
+ us = 0.5 - abs(u)
650
+ k = int(math.floor((2 * a / us + b) * u + lam + 0.43))
651
+ if (us >= 0.07) and (v <= vr):
652
+ return k
653
+ if (k < 0) or ((us < 0.013) and (v > us)):
654
+ continue
655
+ if (math.log(v) + math.log(invalpha) - math.log(a / (us * us) + b)
656
+ <= (-lam + k * loglam - _loggam(k + 1))):
657
+ return k
658
+
659
+ def hypergeometric(self, ngood, nbad, nsample):
660
+ ngood = int(ngood)
661
+ nbad = int(nbad)
662
+ nsample = int(nsample)
663
+ # legacy 验证
664
+ if ngood + nbad < nsample:
665
+ raise ValueError("ngood + nbad < nsample")
666
+ if nsample < 1:
667
+ raise ValueError("nsample < 1 or nsample is NaN")
668
+ # legacy: sample>10 → HRUA, sample>0 → HYP, else 0
669
+ if nsample > 10:
670
+ return self._hgeo_hrua(ngood, nbad, nsample)
671
+ elif nsample > 0:
672
+ return self._hgeo_hyp(ngood, nbad, nsample)
673
+ else:
674
+ return 0
675
+
676
+ def _hgeo_hyp(self, good, bad, sample):
677
+ # random_hypergeometric_hyp
678
+ d1 = bad + good - sample
679
+ d2 = min(bad, good)
680
+ y = float(d2)
681
+ k = sample
682
+ while y > 0.0:
683
+ u = self._u()
684
+ y -= math.floor(u + y / (d1 + k))
685
+ k -= 1
686
+ if k == 0:
687
+ break
688
+ z = int(d2 - y)
689
+ if good > bad:
690
+ z = sample - z
691
+ return z
692
+
693
+ def _hgeo_hrua(self, good, bad, sample):
694
+ # random_hypergeometric_hrua
695
+ mingoodbad = min(good, bad)
696
+ popsize = good + bad
697
+ maxgoodbad = max(good, bad)
698
+ m = min(sample, popsize - sample)
699
+ d4 = mingoodbad / popsize
700
+ d5 = 1.0 - d4
701
+ d6 = m * d4 + 0.5
702
+ d7 = math.sqrt((popsize - m) * sample * d4 * d5 / (popsize - 1) + 0.5)
703
+ d8 = 1.7155277699214135 * d7 + 0.8989161620588988
704
+ d9 = int(math.floor((m + 1) * (mingoodbad + 1) / (popsize + 2)))
705
+ d10 = (_loggam(d9 + 1) + _loggam(mingoodbad - d9 + 1)
706
+ + _loggam(m - d9 + 1) + _loggam(maxgoodbad - m + d9 + 1))
707
+ d11 = min(min(m, mingoodbad) + 1.0, math.floor(d6 + 16 * d7))
708
+ while True:
709
+ x = self._u()
710
+ y = self._u()
711
+ w = d6 + d8 * (y - 0.5) / x
712
+ if (w < 0.0) or (w >= d11):
713
+ continue
714
+ z = int(math.floor(w))
715
+ t = d10 - (_loggam(z + 1) + _loggam(mingoodbad - z + 1)
716
+ + _loggam(m - z + 1) + _loggam(maxgoodbad - m + z + 1))
717
+ if (x * (4.0 - x) - 3.0) <= t:
718
+ break
719
+ if x * (x - t) >= 1:
720
+ continue
721
+ if 2.0 * math.log(x) <= t:
722
+ break
723
+ if good > bad:
724
+ z = m - z
725
+ if m < sample:
726
+ z = good - z
727
+ return z
728
+
729
+ def zipf(self, a, zeta=None):
730
+ if not (a > 1.0):
731
+ raise ValueError("a must be > 1")
732
+ # legacy: rejection (deville)
733
+ am1 = a - 1.0
734
+ b = 2.0 ** am1
735
+ while True:
736
+ u = 1.0 - self._u()
737
+ v = self._u()
738
+ x = math.floor(u ** (-1.0 / am1))
739
+ if x > 9223372036854775807 or x < 1:
740
+ continue
741
+ t = (1.0 + 1.0 / x) ** am1
742
+ if v * x * (t - 1.0) / (b - 1.0) <= t / b:
743
+ return int(x)
744
+
745
+ def logseries(self, p):
746
+ if not (0.0 < p < 1.0):
747
+ raise ValueError("p must be in (0, 1)")
748
+ # legacy
749
+ r = math.log(1.0 - p)
750
+ while True:
751
+ v = self._u()
752
+ if v >= p:
753
+ return 1
754
+ u = self._u()
755
+ q = 1.0 - math.exp(r * u)
756
+ if v <= q * q:
757
+ result = math.floor(1 + math.log(v) / math.log(q))
758
+ if (result < 1) or (v == 0.0):
759
+ continue
760
+ else:
761
+ return int(result)
762
+ if v >= q:
763
+ return 1
764
+ return 2
765
+
766
+ def dirichlet(self, alpha):
767
+ """alpha: 1-d 序列;返回 list(和为 1)。"""
768
+ for x in alpha:
769
+ if not (x > 0.0):
770
+ raise ValueError("alpha <= 0")
771
+ gs = [self._gamma_mt(float(x)) for x in alpha]
772
+ s = sum(gs)
773
+ return [g / s for g in gs]