-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathbernoulli.py
executable file
·1958 lines (1848 loc) · 74.2 KB
/
bernoulli.py
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import random
from fractions import Fraction
class Bernoulli:
"""This class contains methods that generate Bernoulli random numbers,
(either 1 or heads with a given probability, or 0 or tails otherwise).
This class also includes implementations of so-called "Bernoulli factories", algorithms
that sample a new probability given a coin that shows heads with an unknown probability.
Written by Peter O.
References:
- Flajolet, P., Pelletier, M., Soria, M., "On Buffon machines and numbers",
arXiv:0906.5560v2 [math.PR], 2010.
- Huber, M., "Designing perfect simulation algorithms using local correctness",
arXiv:1907.06748v1 [cs.DS], 2019.
- Huber, M., "Nearly optimal Bernoulli factories for linear functions",
arXiv:1308.1562v2 [math.PR], 2014.
- Huber, M., "Optimal linear Bernoulli factories for small mean problems",
arXiv:1507.00843v2 [math.PR], 2016.
- Łatuszyński, K., Kosmidis, I., Papaspiliopoulos, O., Roberts, G.O., "Simulating
events of unknown probabilities via reverse time martingales", arXiv:0907.4018v2
[stat.CO], 2009/2011.
- Goyal, V. and Sigman, K. 2012. On simulating a class of Bernstein
polynomials. ACM Transactions on Modeling and Computer Simulation 22(2),
Article 12 (March 2012), 5 pages.
- Giulio Morina. Krzysztof Łatuszyński. Piotr Nayar. Alex Wendland. "From the Bernoulli factory to a dice enterprise via perfect sampling of Markov chains." Ann. Appl. Probab. 32 (1) 327 - 359, February 2022.
doi.org/10.1214/21-AAP1679
- Dughmi, Shaddin, Jason Hartline, Robert D. Kleinberg, and Rad Niazadeh. "Bernoulli factories and black-box reductions in mechanism design." Journal of the ACM (JACM) 68, no. 2 (2021): 1-30.
- Gonçalves, F. B., Łatuszyński, K. G., Roberts, G. O. (2017). Exact Monte
Carlo likelihood-based inference for jump-diffusion processes.
- Vats, D., Gonçalves, F. B., Łatuszyński, K. G., Roberts, G. O. Efficient
Bernoulli factory MCMC for intractable posteriors, Biometrika 109(2), June 2022.
- Mendo, Luis. "An asymptotically optimal Bernoulli factory for certain
functions that can be expressed as power series." Stochastic Processes and their
Applications 129, no. 11 (2019): 4366-4384.
- Canonne, C., Kamath, G., Steinke, T., "The Discrete Gaussian
for Differential Privacy", arXiv:2004.00010 [cs.DS], 2020.
- Lee, A., Doucet, A. and Łatuszyński, K., 2014. Perfect simulation using
atomic regeneration with application to Sequential Monte Carlo,
arXiv:1407.5770v1 [stat.CO]
"""
def __init__(self):
"""Creates a new instance of the Bernoulli class."""
self.r = random.Random()
self.rbit = -1
self.totalbits = 0
self.debug = False
def _algorithm_a(self, f, m, c):
# B(p) -> B(c*p*(1-(c*p)^(m-1))/(1-(c*p)^m)), or the "gambler's ruin" walk
# (Huber 2016)
s = 1
# if self.debug and self.totalbits!=0: print([m, self.totalbits, float(c), self._coinprob])
while s > 0 and s < m:
if self.debug and self.totalbits >= 5000:
return math.nan
lo = self.logistic(f, c.numerator, c.denominator)
s = s - lo * 2 + 1
return 1 if s == 0 else 0
def _high_power_logistic(self, f, m, beta, c):
# B(p) => B((beta*c*p)^m/(1+(beta*c*p)+...+(beta*c*p)^m)) (Huber 2016)
s = 1
bc = beta * c
while s > 0 and s <= m:
if self.debug and self.totalbits >= 5000:
return math.nan
s = s + self.logistic(f, bc.numerator, bc.denominator) * 2 - 1
return 1 if s == m + 1 else 0
def _henderson_glynn_double_inexact(self, f, n=100):
# Henderson-Glynn doubling scheme. Reference:
# Henderson, S.G., Glynn, P.W., "Nonexistence of a
# Class of Variate Generation Schemes", Operations Research Letters 31 (2), 2001.
x = 0
for i in range(n):
x += f()
lh = Fraction(x, i + 1)
rh = (1 - Fraction(1, i + 1)) / 2
z = min(lh, rh) * 2 # B(p) -> B(2*p - (2*p - E[z])) == B(E[z])
return self.zero_or_one(z.numerator, z.denominator)
def _nacu_peres_double_inexact(self, f, n=100):
# B(p) -> B(2*p - eps), where eps is less than or equal to
# 2*exp(−2*n(1/2−p)^2), and where p is in (0, 1/2). Reference:
# Nacu, Şerban, and Yuval Peres. "Fast simulation of
# new coins from old", The Annals of Applied Probability
# 15, no. 1A (2005): 93-115.
x = 0
for i in range(n):
x += 1 if f() == 1 else -1
if x >= 0:
return 1
if x + (n - 1 - i) < 0:
break # Can't catch up
return 0
def zero_or_one(self, px, py):
"""Returns 1 at probability px/py, 0 otherwise."""
if py <= 0:
raise ValueError
if px == py:
return 1
z = px
while True:
z = z * 2
if z >= py:
if self.randbit() == 0:
return 1
z = z - py
elif z == 0 or self.randbit() == 0:
return 0
def randbit(self):
"""Generates a random bit that is 1 or 0 with equal probability."""
if self.rbit < 0 or self.rbit >= 32:
self.rbit = 0
self.rvalue = self.r.randint(0, (1 << 32) - 1)
ret = (self.rvalue >> self.rbit) & 1
self.rbit += 1
self.totalbits += 1
return ret
def rndint(self, maxInclusive):
if maxInclusive < 0:
raise ValueError("maxInclusive less than 0")
if maxInclusive == 0:
return 0
if maxInclusive == 1:
return self.randbit()
# Lumbroso's fast dice roller method
x = 1
y = 0
while True:
x = x * 2
y = y * 2 + self.randbit()
if x > maxInclusive:
if y <= maxInclusive:
return y
x = x - maxInclusive - 1
y = y - maxInclusive - 1
def _randbits(self, count):
ret = 0
for i in range(count):
ret = (ret << 1) + self.randbit()
return ret
def fill_geometric_bag(self, bag, precision=53):
ret = 0
lb = min(len(bag), precision)
for i in range(lb):
if i >= len(bag) or bag[i] == None:
ret = (ret << 1) | self.randbit()
else:
ret = (ret << 1) | bag[i]
if len(bag) < precision:
diff = precision - len(bag)
ret = (ret << diff) | self._randbits(diff)
# Now we have a number that is a multiple of
# 2^-precision.
return ret / (1 << precision)
def geometric_bag(self, u):
"""Bernoulli factory for a uniformly-distributed random number in (0, 1)
(Flajolet et al. 2010).
- u: List that holds the binary expansion, from left to right, of the uniformly-
distributed random number. Each element of the list is 0, 1, or None (meaning
the digit is not yet known). The list may be expanded as necessary to put
a new digit in the appropriate place in the binary expansion.
"""
r = 0
c = 0
while self.randbit() == 0:
r += 1
while len(u) <= r:
u.append(None)
if u[r] == None:
u[r] = self.randbit()
return u[r]
def zero_or_one_log1p(self, x, y=1):
"""Generates 1 with probability log(1+x/y); 0 otherwise.
Reference: Flajolet et al. 2010. Uses a uniformly-fast special case of
the two-coin Bernoulli factory, rather than the even-parity construction in
Flajolet's paper, which does not have bounded expected running time for all heads probabilities.
"""
bag = []
while True:
if self.randbit() == 0:
return 1
if self.zero_or_one(x, y) == 1 and self.geometric_bag(bag) == 1:
return 0
def zero_or_one_arctan_n_div_n(self, x, y=1):
"""Generates 1 with probability arctan(x/y)*y/x; 0 otherwise.
x/y must be in [0, 1]. Uses a uniformly-fast special case of
the two-coin Bernoulli factory, rather than the even-parity construction in
Flajolet's paper, which does not have bounded expected running time for all heads probabilities.
Reference: Flajolet et al. 2010."""
bag = []
xsq = x * x
ysq = y * y
while True:
if self.randbit() == 0:
return 1
if (
self.zero_or_one(xsq, ysq) == 1
and self.geometric_bag(bag) == 1
and self.geometric_bag(bag) == 1
):
return 0
def arctan_n_div_n(self, f):
"""Arctan div N: B(p) -> B(arctan(p)/p). Uses a uniformly-fast special case of
the two-coin Bernoulli factory, rather than the even-parity construction in
Flajolet's paper, which does not have bounded expected running time for all heads probabilities.
Reference: Flajolet et al. 2010.
- f: Function that returns 1 if heads and 0 if tails.
"""
bag = []
while True:
if self.randbit() == 0:
return 1
if (
f() == 0
and self.geometric_bag(bag) == 0
and f() == 0
and self.geometric_bag(bag) == 0
):
return 0
def zero_or_one_pi_div_4(self):
"""Generates 1 with probability pi/4.
Reference: Flajolet et al. 2010.
"""
r = self.rndintexc(6)
if r < 3:
return self.zero_or_one_arctan_n_div_n(1, 2)
else:
return 1 if r < 5 and self.zero_or_one_arctan_n_div_n(1, 3) == 1 else 0
def one_div_pi(self):
"""Generates 1 with probability 1/pi.
Reference: Flajolet et al. 2010.
"""
t = 0
while self.zero_or_one(1, 4) == 0:
t += 1
while self.zero_or_one(1, 4) == 0:
t += 1
if self.zero_or_one(5, 9):
t += 1
if t == 0:
return 1
for i in range(3):
s = sum(self.randbit() for j in t * 2)
if s != t:
return 0
return 1
def _uniform_less_nd(self, bag, num, den):
"""Determines whether a uniformly-distributed random number
(given as an incomplete binary expansion that is built up
as necessary) is less than the specified fraction (in the interval [0, 1])
expressed as a numerator and denominator."""
a = num
if num == 0:
return 0
b = den
if num == den:
return 1
pt = 1
i = 0
while True:
while len(bag) <= i:
bag.append(self.randbit())
if bag[i] == None:
bag[i] = self.randbit()
mybit = bag[i]
# Determine whether frac >= 2**-pt
cmpare = (a << pt) >= b
# if cmpare!=(frac>=Fraction(1,1<<pt)): raise ValueError
bit = 1 if cmpare else 0
if mybit == 0 and bit == 1:
return 1
if mybit == 1 and bit == 0:
return 0
if bit == 1:
# Subtract 2**-pt from frac
a = (a << pt) - b
b <<= pt
# Frac is now 0, so result can only be 0
if a == 0:
return 0
pt += 1
i += 1
return 0
def _uniform_less(self, bag, frac):
"""Determines whether a uniformly-distributed random number
(given as an incomplete binary expansion that is built up
as necessary) is less than the specified Fraction (in the interval [0, 1])."""
frac = frac if isinstance(frac, Fraction) else Fraction(frac)
# NOTE: Fractions are not compared and subtracted directly because
# doing so is very costly in Python
return self._uniform_less_nd(bag, frac.numerator, frac.denominator)
def bernoulli_x(self, f, x):
"""Bernoulli factory with a given probability: B(p) => B(x) (Mendo 2019).
Mendo calls Bernoulli factories "nonrandomized" if their randomness
is based entirely on the underlying coin.
- f: Function that returns 1 if heads and 0 if tails.
- x: Desired probability, in [0, 1]."""
pw = Fraction(x)
if pw == 0:
return 0
if pw == 1:
return 1
pt = Fraction(1, 2)
while True:
y = f()
z = f()
if y == 1 and z == 0:
return 1 if pw >= pt else 0
elif y == 0 and z == 1:
if pw >= pt:
pw -= pt
pt /= 2
def coin(self, c):
"""Convenience method to generate a function that returns
1 (heads) with the specified probability c (which must be in [0, 1])
and 0 (tails) otherwise."""
if c == 0:
return lambda: 0
if c == 1:
return lambda: 1
c = Fraction(c)
return lambda: self.zero_or_one(c.numerator, c.denominator)
def complement(self, f):
"""Complement (NOT): B(p) => B(1-p) (Flajolet et al. 2010)
- f: Function that returns 1 if heads and 0 if tails.
"""
return f() ^ 1
def square(self, f1, f2):
"""Square: B(p) => B(1-p). (Flajolet et al. 2010)
- f1, f2: Functions that return 1 if heads and 0 if tails.
"""
return 1 if f1() == 1 and f1() == 1 else 0
def product(self, f1, f2):
"""Product (conjunction; AND): B(p), B(q) => B(p*q) (Flajolet et al. 2010)
- f1, f2: Functions that return 1 if heads and 0 if tails.
"""
return 1 if f1() == 1 and f2() == 1 else 0
def disjunction(self, f1, f2):
"""Disjunction (OR): B(p), B(q) => B(p+q-p*q) (Flajolet et al. 2010)
- f1, f2: Functions that return 1 if heads and 0 if tails.
"""
return 1 if f1() == 1 or f2() == 1 else 0
def mean(self, f1, f2):
"""Mean: B(p), B(q) => B((p+q)/2) (Flajolet et al. 2010)
- f1, f2: Functions that return 1 if heads and 0 if tails.
"""
return f1() if self.randbit() == 0 else f2()
def conditional(self, f1, f2, f3):
"""Conditional: B(p), B(q), B(r) => B((1-r)*q+r*p) (Flajolet et al. 2010)
- f1, f2, f3: Functions that return 1 if heads and 0 if tails.
"""
return f1() if f3() == 1 else f2()
def evenparity(self, f):
"""Even parity: B(p) => B(1/(1+p)) (Flajolet et al. 2010)
- f: Function that returns 1 if heads and 0 if tails.
Note that this function is slow as the probability of heads approaches 1.
"""
while True:
if f() == 0:
return 1
if f() == 0:
return 0
def divoneplus(self, f):
"""Divided by one plus p: B(p) => B(1/(1+p)), implemented
as a special case of the two-coin construction. Prefer over even-parity
for having bounded expected running time for all heads probabilities.
- f: Function that returns 1 if heads and 0 if tails.
Note that this function is slow as the probability of heads approaches 1.
"""
while True:
if self.randbit() == 0:
return 1
if f() == 1:
return 0
def logistic(self, f, cx=1, cy=1):
"""Logistic Bernoulli factory: B(p) -> B(cx*p/(cy+cx*p)) or
B(p) -> B((cx/cy)*p/(1+(cx/cy)*p)) (Morina et al. 2019)
- f: Function that returns 1 if heads and 0 if tails. Note that this function can
be slow as the probability of heads approaches 0.
- cx, cy: numerator and denominator of c; the probability of heads (p) is multiplied
by c. c must be in (0, 1).
"""
c = Fraction(cx, cy)
while True:
if self.zero_or_one(c.denominator, c.numerator + c.denominator) == 1:
return 0
elif f() == 1:
return 1
def _multilogistic_inexact(self, fa, ca):
# Huber 2016, replaces logistic(f, c) in linear Bernoulli factory to make a multivariate
# Bernoulli factory of the form B(p1), ..., B(pn) -> B(c1*p1 + ... + cn*pn).
# For this method:
# B(p1), ..., B(pn) -> B(r/(1+r)), where r = c1*p1 + ... + cn*pn and r is bounded away
# from 1 (notice that c1, ..., cn need not be in [0, 1]).
x = 0
a = -math.log(self.r.random())
t = [0 for i in range(len(fa))]
for i in range(len(fa)):
t[i] = -math.log(self.r.random()) / ca[i]
while x == 0 and t[i] < a:
if fa[i]() == 1:
return 1
t[i] -= math.log(self.r.random()) / ca[i]
return 0
def eps_div(self, f, eps):
"""Bernoulli factory as follows: B(p) -> B(eps/p) (Lee et al. 2014).
- f: Function that returns 1 if heads and 0 if tails.
- eps: Fraction in (0, 1), must be chosen so that eps < p, where p is
the probability of heads."""
if eps == 0:
return 0
if eps < 0:
raise ValueError
eps = Fraction(eps)
ceps = Fraction(1) / (1 - Fraction(eps))
cgamma = None
# Proposition 4 of Lee et al. 2014
half = Fraction(1, 2)
if eps >= half:
beta = half
cgamma = 1 - (1 - beta) / (1 - Fraction(1, 4))
else:
beta = eps * 2
cgamma = 1 - (1 - beta) / (1 - eps)
finv = lambda: (f() ^ 1)
while True:
if self.zero_or_one(eps.numerator, eps.denominator) == 1:
return 1
# Sample B((p-eps)/(1-eps)) or B(1-(1-p)/(1-eps))
b = self.linear(finv, ceps.numerator, ceps.denominator, cgamma)
if b == 0:
return 0
def zero_or_one_exp_minus(self, x, y):
"""Generates 1 with probability exp(-x/y); 0 otherwise.
Reference: Canonne et al. 2020."""
if y <= 0 or x < 0:
raise ValueError
if x == 0:
return 1
if x > y:
xf = int(x / y) # Get integer part
x = x % y # Reduce to fraction
if x > 0 and self.zero_or_one_exp_minus(x, y) == 0:
return 0
for i in range(xf):
if self.zero_or_one_exp_minus(1, 1) == 0:
return 0
return 1
r = 1
oy = y
while True:
if self.zero_or_one(x, y) == 0:
return r
r = 1 - r
y = y + oy
def rndintexc(self, maxexc):
"""Returns a random integer in [0, maxexc)."""
if maxexc <= 0:
raise ValueError
if maxexc == 1:
return 0
maxinc = maxexc - 1
x = 1
y = 0
while True:
x *= 2
y = y * 2 + self.randbit()
if x > maxinc:
if y <= maxinc:
return y
x = x - maxinc - 1
y = y - maxinc - 1
def probgenfunc(self, f, rng):
"""Probability generating function Bernoulli factory: B(p) => B(E[p^x]), where x is rng()
(Dughmi et al. 2021). E[p^x] is the expected value of p^x and is also known
as the probability generating function.
- f: Function that returns 1 if heads and 0 if tails.
- rng: Function that returns a nonnegative integer at random.
Example (Dughmi et al. 2021): if 'rng' is Poisson(lamda) we have
an "exponentiation" Bernoulli factory as follows:
B(p) => B(exp(p*lamda-lamda))
"""
n = rng()
for i in range(n):
if f() == 0:
return 0
return 1
def powerseries(self, f):
"""Power series Bernoulli factory: B(p) => B(1 - c(0)*(1-p) + c(1)*(1-p)^2 +
c(2)*(1-p)^3 + ...), where c(i) = `c[i]/sum(c)`) (Mendo 2019).
- f: Function that returns 1 if heads and 0 if tails.
- c: List of coefficients in the power series, all of which must be
nonnegative integers."""
i = 0
csum = sum(c)
dsum = 0
while True:
x = f()
if x == 1:
return 1
ci = Fraction(0) if i >= c.length else Fraction(c[i], csum)
d = ci / (1 - dsum)
if d == 1 or self.zero_or_one(d.numerator, d.denominator) == 1:
return 0
dsum += ci
i += 1
def power(self, f, ax, ay=1):
"""Power Bernoulli factory: B(p) => B(p^(ax/ay)). (case of (0, 1) provided by
Mendo 2019).
- f: Function that returns 1 if heads and 0 if tails.
- ax, ay: numerator and denominator of the desired power to raise the probability
of heads to. This power must be 0 or greater."""
a = None
if ay == 1 and isinstance(ax, Fraction):
a = ax
ax = a.numerator
ay = a.denominator
elif not (isinstance(ax, int) and isinstance(ay, int)):
a = Fraction(ax, ay)
ax = a.numerator
ay = a.denominator
if (ax < 0) ^ (ay < 0) or ay == 0: # Denominator is 0 or power is negative
raise ValueError
if ax == 0:
return 1
if ax == ay:
return f()
if ax > ay:
# (px/py)^(ax/ay) -> (px/py)^int(ax/ay) * (px/py)^frac(ax/ay)
xf = int(ax / ay) # Get integer part
nx = ax % ay # Reduce to fraction
if nx > 0:
# Split 1 plus the fractional part in two pieces, so that the fractional
# parts involved in power_frac are closer to 1, and so are processed
# much faster by power_frac. Compensate by reducing the
# integer part by 1.
xf -= 1
nx += ay
nxpart = int(nx / 2)
if (
self.power(f, nxpart, ay) == 0
or self.power(f, nx - nxpart, ay) == 0
):
return 0
if xf > 0:
for i in range(xf):
if f() == 0:
return 0
return 1
# Following is algorithm from Mendo 2019
i = 1
while True:
if f() == 1:
return 1
if self.zero_or_one(ax, ay * i) == 1:
return 0
i = i + 1
def a_div_b_bag(self, numerator, intpart, bag):
"""Simulates numerator/(intpart+bag)."""
while True:
if self.zero_or_one(intpart, 1 + intpart) == 1:
return self.zero_or_one(numerator, intpart)
if self.geometric_bag(bag) == 1:
return 0
def a_bag_div_b_bag(selfnumerator, numbag, intpart, bag):
"""Simulates (numerator+numbag)/(intpart+bag)."""
while True:
if self.zero_or_one(intpart, 1 + intpart) == 1:
while True:
i = self.rndintexc(intpart)
if i < numerator:
return 1
if i == numerator:
return self.geometric_bag(numbag)
if self.geometric_bag(bag) == 1:
return 0
def _zero_or_one_power_frac(self, px, py, nx, ny):
# Generates a random number, namely 1 with
# probability (px/py)^(nx/ny) (where nx/ny is in (0, 1)),
# and 1 otherwise. Returns 1 if nx/ny is 0. Reference: Mendo 2019.
i = 1
while True:
if self.debug and self.totalbits >= 5000:
return math.nan
x = self.zero_or_one(px, py)
if x == 1:
return 1
if self.zero_or_one(nx, ny * i) == 1:
return 0
i = i + 1
def zero_or_one_power_ratio(self, px, py, nx, ny):
"""Generates 1 with probability (px/py)^(nx/ny) (where nx/ny can be
positive, negative, or zero); 0 otherwise."""
if py <= 0 or px < 0:
raise ValueError
n = Fraction(nx, ny)
p = Fraction(px, py)
nx = n.numerator
ny = n.denominator
px = p.numerator
py = p.denominator
if self.debug and self.totalbits >= 5000:
return math.nan
if n < 0: # (px/py)^(nx/ny) -> (py/px)^-(nx/ny)
n = -n
return self.zero_or_one_power_ratio(py, px, n.numerator, n.denominator)
if n == 0 or px >= py:
return 1
if nx == ny:
return self.zero_or_one(px, py)
if nx > ny:
# (px/py)^(nx/ny) -> (px/py)^int(nx/ny) * (px/py)^frac(nx/ny)
xf = int(nx / ny) # Get integer part
nx = nx % ny # Reduce to fraction
if nx > 0:
# Split 1 plus the fractional part in two pieces, so that the fractional
# parts involved in power_frac are closer to 1, and so are processed
# much faster by power_frac. Compensate by reducing the
# integer part by 1.
xf -= 1
nx += ny
nxpart = int(nx / 2)
if (
self._zero_or_one_power_frac(nxpart, ny) == 0
or self._zero_or_one_power_frac(nx - nxpart, ny) == 0
):
return 0
if xf >= 1:
n1 = 1
npx = px
npy = py
while n1 < xf and px < (1 << 32) and py < (1 << 32):
npx *= px
npy *= py
n1 += 1
if n1 > 1:
quo = int(xf / n1)
if self.zero_or_one_power(npx, npy, quo) == 0:
return 0
xf -= quo * n1
for i in range(xf):
if self.debug and self.totalbits >= 5000:
return math.nan
if self.zero_or_one(px, py) == 0:
return 0
return 1
return self._zero_or_one_power_frac(px, py, nx, ny)
def zero_or_one_power(self, px, py, n):
"""Generates 1 with probability (px/py)^n (where n can be
positive, negative, or zero); 0 otherwise."""
return self.zero_or_one_power_ratio(px, py, n, 1)
def twocoin(self, f1, f2, c1=1, c2=1, beta=1):
"""Two-coin Bernoulli factory: B(p), B(q) =>
B(c1*p*beta / (beta * (c1*p+c2*q) - (beta - 1)*(c1+c2)))
(Gonçalves et al. 2017, Vats et al. 2020; in Vats et al.,
C1,p1 corresponds to cy and C2,p2 corresponds to cx).
Logistic Bernoulli factory is a special case with q=1, c2=1, beta=1.
- f1, f2: Functions that return 1 if heads and 0 if tails.
- c1, c2: Factors to multiply the probabilities of heads for f1 and f2, respectively.
- beta: Early rejection parameter ("portkey" two-coin factory).
When beta = 1, the formula simplifies to B(c1*p/(c1*p+c2*q)).
"""
cx = Fraction(c1) / (Fraction(c1) + Fraction(c2))
beta = Fraction(beta)
while True:
if beta != 1:
if self.zero_or_one(beta.numerator, beta.denominator) == 0:
return 0
if self.zero_or_one(cx.numerator, cx.denominator) == 1:
if f1() == 1:
return 1
else:
if f2() == 1:
return 0
def sin(self, f):
"""Sine Bernoulli factory: B(p) => B(sin(p)). Special
case of Algorithm3 of reverse-time martingale paper.
"""
if f() == 0:
return 0
u = Fraction(1)
l = Fraction(0)
w = Fraction(1)
bag = []
fac = 6
n = 1
while True:
if self.debug and self.totalbits >= 5000:
return math.nan
# print([fac,math.factorial(2*n)])
if w != 0:
w *= f()
if w != 0:
w *= f()
if n % 2 == 0:
u = l + w / fac
else:
l = u - w / fac
if self._uniform_less(bag, l) == 1:
return 1
if self._uniform_less(bag, u) == 0:
return 0
n += 1
fac *= (n * 2) * (n * 2 + 1)
def martingale(self, coin, coeff):
"""General martingale algorithm for alternating power
series.
'coin' is the coin to be flipped; 'coeff' is a function
that takes an index 'i' and calculates the coefficient
for index 'i'. Indices start at 0."""
u = Fraction(coeff(0))
l = Fraction(0)
w = Fraction(1)
bag = []
n = 1
while True:
if w != 0:
w *= coin()
coef = coeff(n)
if coef > 0:
u = l + w * coef
else:
l = u - w * abs(coef)
if self._uniform_less(bag, l) == 1:
return 1
if self._uniform_less(bag, u) == 0:
return 0
n += 1
def cos(self, f):
"""Cosine Bernoulli factory: B(p) => B(cos(p)). Special
case of Algorithm3 of reverse-time martingale paper.
"""
u = Fraction(1)
l = Fraction(0)
w = Fraction(1)
bag = []
fac = 2
n = 1
while True:
if self.debug and self.totalbits >= 5000:
return math.nan
# print([fac,math.factorial(2*n)])
if w != 0:
w *= f()
if w != 0:
w *= f()
if n % 2 == 0:
u = l + w / fac
else:
l = u - w / fac
if self._uniform_less(bag, l) == 1:
return 1
if self._uniform_less(bag, u) == 0:
return 0
n += 1
fac *= (n * 2 - 1) * (n * 2)
def add(self, f1, f2, eps=Fraction(5, 100)):
"""Addition Bernoulli factory: B(p), B(q) => B(p+q) (Dughmi et al. 2021)
- f1, f2: Functions that return 1 if heads and 0 if tails.
- eps: A Fraction in (0, 1). eps must be chosen so that p+q <= 1 - eps,
where p and q are the probability of heads for f1 and f2, respectively.
"""
fv = lambda: self.mean(f1, f2)
return self.linear(fv, 2, 1)
def old_linear(self, f, cx, cy=1, eps=Fraction(5, 100)):
"""Linear Bernoulli factory: B(p) => B((cx/cy)*p). Older algorithm given in (Huber 2014).
- f: Function that returns 1 if heads and 0 if tails.
- cx, cy: numerator and denominator of c; the probability of heads (p) is multiplied
by c. c must be 0 or greater. If c > 1, c must be chosen so that c*p < 1 - eps.
- eps: A Fraction in (0, 1). If c > 1, eps must be chosen so that c*p < 1 - eps.
"""
if cy == 1:
c = Fraction(cx)
else:
c = Fraction(cx, cy)
# Fast cases, not covered in Huber, to make this more general than c > 1
if c < 0:
raise ValueError
if c == 0:
return 0
if c == 1:
return f()
if c.numerator < c.denominator:
# B(p) -> B(c*p), where c is in (0, 1)
return (
1
if self.zero_or_one(c.numerator, c.denominator) == 1 and f() == 1
else 0
)
gamma = Fraction(1, 2)
eps = Fraction(eps)
if eps <= 0:
raise ValueError
k = Fraction(23, 10) / (gamma * eps)
eps = min(eps, Fraction(644, 1000))
i = 1
while True:
ce = (c - 1) / c
cn = ce.numerator
cd = ce.denominator
while True:
# print([i,self.totalbits,float(self._coinprob),"k",float(k)])
if self.debug and self.totalbits >= 5000:
return math.nan
i -= 1
if f() == 0:
# Number of failures before first success, plus 1
i += 1
while self.zero_or_one(cn, cd) == 0:
if self.debug and self.totalbits >= 5000:
return math.nan
i += 1
if i == 0:
return 1
if i >= k:
break
if i >= k:
ce = 1 + gamma * eps
if ce < 1:
raise ValueError
if self.debug and self.totalbits >= 5000:
return math.nan
# print(float(ce),float(ce**-i),float((1/ce)**i))
if self.zero_or_one_power(ce.denominator, ce.numerator, i) == 0:
return 1 if i == 0 else 0
c *= ce
eps *= 1 - gamma
k /= 1 - gamma
if i == 0:
return 1
def linear(self, f, cx, cy=1, eps=Fraction(5, 100)):
"""Linear Bernoulli factory: B(p) => B((cx/cy)*p) (Huber 2016).
- f: Function that returns 1 if heads and 0 if tails.
- cx, cy: numerator and denominator of c; the probability of heads (p) is multiplied
by c. c must be 0 or greater. If c > 1, c must be chosen so that c*p <= 1 - eps.
- eps: A Fraction in (0, 1). If c > 1, eps must be chosen so that c*p <= 1 - eps.
"""
if cy == 1:
c = Fraction(cx)
else:
c = Fraction(cx, cy)
# Fast cases, not covered in Huber, to make this more general than c > 1
if c < 0:
raise ValueError
if c == 0:
return 0
if c == 1:
return f()
if c.numerator < c.denominator:
# B(p) -> B(c*p), where c is in (0, 1)
return (
1
if self.zero_or_one(c.numerator, c.denominator) == 1 and f() == 1
else 0
)
eps = Fraction(eps)
if eps <= 0:
raise ValueError
m = (Fraction(9, 2) / eps) + 1
# Ceiling operation
m += Fraction(m.denominator - m.numerator % m.denominator, m.denominator)
m = int(m)
beta = 1 + Fraction(1) / (m - 1)
if self.debug and self.totalbits >= 5000:
return math.nan
if self._algorithm_a(f, m, beta * c) == 0:
if self.debug and self.totalbits >= 5000:
return math.nan
return 0
if self.zero_or_one(beta.denominator, beta.numerator) == 1:
if self.debug and self.totalbits >= 5000:
return math.nan
return 1 # Bern(1/beta)
bc = beta * c
while True:
if self.debug and self.totalbits >= 5000:
return math.nan
if (
self.linear(f, bc.numerator, bc.denominator, eps=1 - beta * (1 - eps))
== 0
):
if self.debug and self.totalbits >= 5000:
return math.nan
return 0
if self._high_power_logistic(f, m - 2, beta, c) == 1:
if self.debug and self.totalbits >= 5000:
return math.nan
return 1
m -= 1
def bernstein(self, f, alpha):
"""Polynomial Bernoulli factory: B(p) => B(Bernstein(alpha))
(Goyal and Sigman 2012).
- f: Function that returns 1 if heads and 0 if tails.
- alpha: List of Bernstein coefficients for the polynomial (when written
in Bernstein form),
whose degree is this list's length minus 1.
For this to work, each coefficient must be in [0, 1]."""
for a in alpha:
if a < 0 or a > 1:
raise ValueError
j = sum([f() for i in range(len(alpha) - 1)])
return 1 if self._uniform_less([], alpha[j]) == 1 else 0
def exp_minus_ext(self, f, c=0):
"""
Extension to the exp-minus Bernoulli factory of (Łatuszyński et al. 2011):
B(p) -> B(exp(-p - c))
To the best of my knowledge, I am not aware
of any article or paper that presents this particular
Bernoulli factory (before my articles presenting
accurate beta and exponential generators).
- f: Function that returns 1 if heads and 0 if tails.
- c: Integer part of exp-minus. Default is 0.
"""
if self.zero_or_one_exp_minus(c, 1) == 0:
return 0
return self.exp_minus(f)
def alt_series(self, f, series):
"""
Alternating-series Bernoulli factory: B(p) -> B(s[0] - s[1]*p + s[2]*p^2 - ...)
(Łatuszyński et al. 2011).
- f: Function that returns 1 if heads and 0 if tails.
- series: Object that generates each coefficient of the series starting with the first.
Each coefficient must be less than or equal to the previous and all of them must
be 1 or less.
Implements the following two methods: reset() resets the object to the first
coefficient; and next() generates the next coefficient.
"""
series.reset()
u = Fraction(1) * series.next()
l = Fraction(0)
w = Fraction(1)
bag = []
n = 1
while True:
if w != 0:
w *= f()
if n % 2 == 0:
u = l + w * series.next()
else:
l = u - w * series.next()
if self._uniform_less(bag, l) == 1:
return 1
if self._uniform_less(bag, u) == 0:
return 0
n += 1
def exp_minus(self, f):
"""
Exp-minus Bernoulli factory: B(p) -> B(exp(-p)) (Łatuszyński et al. 2011).