RandomLib
1.10
|
Return true with probability 1/π. More...
#include <RandomLib/InversePiProb.hpp>
Public Member Functions | |
template<class Random > | |
bool | operator() (Random &r) |
Return true with probability 1/π.
InversePiProb p; p(Random& r) returns true with prob 1/π using the method of Flajolet et al. It consumes 9.6365 bits per call on average.
The method is given in Section 3.3 of
using the identity
\[ \frac 1\pi = \sum_{n=0}^\infty {{2n}\choose n}^3 \frac{6n+1}{2^{8n+2}} \]
It is based on the expression for 1/π given by Eq. (28) of
\[\frac4\pi = 1 + \frac74 \biggl(\frac 12 \biggr)^3 + \frac{13}{4^2} \biggl(\frac {1\cdot3}{2\cdot4} \biggr)^3 + \frac{19}{4^3} \biggl(\frac {1\cdot3\cdot5}{2\cdot4\cdot6} \biggr)^3 + \ldots \]
The following is a description of how to carry out the algorithm "by hand" with a real coin, together with a worked example:
HHHHT
; HHHT
; HHT
. Let h1 = 4, h2 = 3, h3 = 2 be the numbers of heads tossed in each experiment.0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 h 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 floor(h1/2) 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 floor(h2/2) 1 0 0 0 1 1 1 0 0 0 1 1 1 0 0 0 1 1 mod(floor((h3-1)/3), 2)
TTHHTH
; HHTHH|H
; THHHHH
. Are the number of heads and tails equal in each experiment? yes and no and no → false. (Here, you can give up at the |.)The final result in this example is false. The most common way a true result is obtained is with n = 0, in which case the last step vacuously returns true.
Proof of the algorithm: Flajolet et al. rearrange Ramanujan's identity as
\[ \frac 1\pi = \sum_{n=0}^\infty \biggl[{2n\choose n} \frac1{2^{2n}} \biggr]^3 \frac{6n+1}{2^{2n+2}}. \]
Noticing that
\[ \sum_{n=0}^\infty \frac{6n+1}{2^{2n+2}} = 1, \]
the algorithm becomes:
Implement (1) as
Implement (2) as the outcome of 3 coin tossing experiments of 2n tosses with success defined as equal numbers of heads and tails in each trial.
This class illustrates how to return an exact result using coin tosses only. A more efficient implementation (which is still exact) would replace prob59 by r.Prob(5,9) and geom4 by LeadingZeros z; z(r)/2.
Definition at line 104 of file InversePiProb.hpp.
|
inline |
Return true with probability 1/π.
Random | the type of the random generator. |
[in,out] | r | a random generator. |
Definition at line 140 of file InversePiProb.hpp.