WorksMathematics
Exact Sampling of Almost Surely Finite Sequences of Independent Events
Abstract
We consider infinite sequences of independent events whose probabilities are summable, so that almost surely only finitely many of the events occur. We present an algorithm which exactly samples the set of events which occur, using a finite number of steps. The algorithm works by generating proposals from a Poisson process, followed by a rejection step. We illustrate use of the algorithm with the help of three applications: prime factorisation of zeta-distributed random integers, random integer partitions and convex lattice polygonal lines.
Introduction
Consider a sequence of independent Bernoulli random variables , such that we have for all . If we assume that , the Borel–Cantelli lemma guarantees that, almost surely (a.s.), the events happen only for finitely many . Thus, while there are infinitely many in the sequence, an exact representation of a random sample from the sequence can be stored using only a finite amount of computer memory. Here we show that in many cases it is possible to exactly sample random instances of . The main obstacle to overcome is the fact that the position of the last non-zero is determined by the infinite tail of the random sequence.
As a simple example, let for all . Since , the series is convergent. In this case, it is easy to compute the distribution of the index of the last non-zero . Set , then we have
Note that for (which means that all are zero) this gives a correct answer, . More generally, for
Hence, we can first sample the random number according to its distribution (1) and then sample independent Bernoulli random variables (with by definition of ). This gives an exact sampling algorithm, but to generalise it we need to be able to calculate explicitly the infinite products of the form , which is not always possible.
As a pragmatic alternative, we consider a straightforward but approximate algorithm.
Algorithm 0.
Choose large.
For , generate independently with .
Set for all .
In the output of Algorithm 0, the events are independent. For we have as required, but for we have . If we choose large enough that is ‘small’ for all , we can use Algorithm 0 as an approximate solution to our problem. Our aim is to present an algorithm (using only finitely many steps) which can exactly sample from the full sequence of events, corresponding to the case in Algorithm 0.
Sequences of this kind appear in the study of random combinatorial structures. An integer partition can be described by the numbers of parts of each size and, for suitable probability measures on the set of all partitions, these numbers are independent random variables of which only finitely many are non-zero [14, 23, 7]. Convex lattice polygonal lines can be described in the same way, using the multiplicities of the sides in each possible direction [22, 9]. A further example is the occupancy problem with infinitely many boxes, where a Poisson distributed number of balls makes the numbers of balls in different boxes independent [15, 8]. Our algorithm is based on this last observation.
For combinatorial structures, exact sampling is often considered in the framework of Boltzmann samplers, introduced by Duchon et al. [12]. Such a sampler generates an object of random size, in such a way that all objects of the same size are equally likely. Flajolet et al. [13] extend the framework to unlabelled structures, including multisets and powersets; their samplers assume that an oracle for the values of the generating functions is available. If an object of a given size is required, the output of the sampler can be rejected until the size is correct, and Arratia and DeSalvo [3] and DeSalvo [10] show how the cost of this rejection step can be reduced. Our method uses two older ideas. The first idea is the thinning method of Lewis and Shedler [19], which simulates a Poisson process by generating the points of a process with larger intensity and then deleting some of these points at random. The second idea is retrospective sampling, which Beskos et al. [5] use for the exact simulation of a class of diffusions: there, an infinite-dimensional object is simulated exactly by generating only the finitely many random variables which are needed to determine the output.
A related construction appears in parallel work by Peyen [20], who considers the probabilities , with several independent events for each , in order to obtain Boltzmann samplers for powersets. There, the independence of the events is derived from an occupancy model with a Poisson distributed number of balls, and the rejection step is justified using the thinning method for Poisson processes. Peyen [20] also shows that, in such an occupancy model with infinitely many boxes, the Poisson distribution is the only distribution for the number of balls which makes the events uncorrelated. The focus of the present article is different: we state the method for arbitrary summable probabilities , give a self-contained proof based on Poisson processes, and consider examples outside the setting of Boltzmann samplers.
Section 2 introduces the main results of the article, namely Algorithm 1, the correctness proof in Lemma 1 and the efficiency analysis in Lemma 2. In section 3 we apply the method to three examples: the prime factorisation of zeta-distributed random integers, random integer partitions and convex lattice polygonal lines. In the first of these examples the probabilities decay so slowly that Algorithm 0 is not feasible when the parameter of the distribution is close to 1, whereas the expected cost of the exact algorithm is polynomial. To our knowledge, this gives the first exact sampler for factored, zeta-distributed integers.
Exact Sampling
The following algorithm gives an exact solution for the sampling problem described in the introduction.
The Algorithm
Algorithm 1. Choose probability weights such that for all and such that there exists an with for all . Then perform the following steps:
Generate .
Generate , independently, such that for all and all .
Generate , independently, uniformly distributed.
For all , set if there is a with and , and set otherwise.
Figure 1 illustrates the algorithm. Steps 1 to 3 generate random points in the strip , and step 4 accepts the points which satisfy . We have if and only if at least one of the accepted points has first coordinate .
Figure 1. One run of Algorithm 1 for and with , as in Example 2. Each point is shown as a circle at height in column . The circle is filled if , and we have if and only if column contains at least one filled circle.
To use the algorithm, we need to choose probability weights which satisfy the assumptions stated at the start of the algorithm. Under the assumptions and , a suitable distribution always exists. For example, it is easy to show that
and thus is a valid choice. The following lemma shows that the algorithm works as intended.
Lemma 1. Given with for all and , let be the sequence of random variables constructed by Algorithm 1. Then the are independent, with for all .
The proof, loosely inspired by Beskos et al. [5], is a nice application of Poisson processes. For reference we summarise the required results here, leaving measurability considerations aside. Full details can be found, for example, in the monograph by Kingman [18]. In the following, denotes the number of elements in a finite or countable set .
Definition 1. Let be a set and a measure on such that for all . A Poisson process on with intensity measure is a random subset of such that
for each and any disjoint sets , the random variables are independent, and
for every , the random variable is Poisson distributed with parameter .
In the proof of Lemma 1, below, we will use the fact that the constructed in the algorithm form a Poisson process. This follows from the same argument as is used in the existence proof of Poisson processes: Assume that and that are independent random variables such that and
for all . Define . Let be disjoint. Then
(We leave some of the steps as an exercise to the reader.) This shows that the are independent and Poisson distributed, and thus that is indeed a Poisson process.
Proof of Lemma 1. Let and consider the product measure on , where denotes the Lebesgue measure on . Then we have and has no atoms. For the purpose of the proof we extend the and from the algorithm to infinite sequences and , where all , are independent of each other and of . From the algorithm we recall that and that the are uniformly distributed on . Since
for all and all , the construction preceding this proof shows that the random set
is a Poisson process with intensity measure on .
By definition of we have . Consider the sets
for all . In Figure 1, these sets form the shaded parts of the columns. By step 4 of the algorithm we have
Since is a Poisson process and since the sets are disjoint, it follows that the random variables are independent.
To show that the have the correct distribution, we first write
Using the properties of a Poisson process again we get
and thus
as required. This completes the proof.
The following two examples illustrate the algorithm. In the first example every point is accepted, while in the second example some of the points are rejected.
Example 1. In the introduction we considered the case for all . Here we have and thus . We choose , so that is the geometric distribution with parameter . This gives for all , and we can choose . Since the condition in step 4 is then always satisfied, the are not needed and the algorithm takes the following form: we generate , then we generate independently from the geometric distribution , and finally we set if and only if .
Example 2. Let and . Then we have , so the method can be applied. Choose to be the geometric distribution with parameter , that is, for all . Then we have
where for all . Since , the function is monotonically increasing. Thus, the sequence is monotonically decreasing and we can choose
Using this value of , it is easy to implement the method on a computer. One run of the method, for , is shown in Figure 1.
Efficiency
When implementing the algorithm on a computer, the proposal distribution should be chosen so that the samples in step 2 can be generated efficiently.
Lemma 2. A run of Algorithm 1 consumes random numbers, where . In particular, the expected number of random numbers consumed is .
Proof. Step 1 of the algorithm consumes one random number, namely , and steps 2 and 3 consume random numbers each. Step 4 consumes no random numbers. Finally, we have . This completes the proof. □
If each of the random numbers can be generated in a bounded amount of time, and if the same holds for the evaluation of , the lemma shows that the expected running time and the expected memory use of Algorithm 1 are bounded by a constant times . The algorithm works for any value of the upper bound , but in the light of Lemma 2 the bound should be chosen as small as possible.
The constant , defined before Lemma 1, is a lower bound for . Since and for all , we have
for every choice of and which satisfies the conditions of Algorithm 1. Equality holds if and only if for all , and this is the case only for the choice . In the general case we have
for every , and thus the ratio is the probability that a point is accepted. Thus, the expected number of accepted points is . The algorithm thus generates points on average in order to obtain accepted points.
The choice minimises the cost, but it can only be used when samples from this distribution can be generated efficiently. This is the case in Example 1, where we have and every point is accepted. In the other examples in this article we choose a distribution which is easy to sample from, and we then have .
Example 3. To compare efficiency of the algorithms 0 and 1, we use the number of random samples consumed as a measure for the resource cost of the methods here. Clearly, Algorithm 0 consumes exactly random variables, and the value increases as the probability of missing one or more events decreases. From Lemma 2 we know that Algorithm 1 uses samples where , so the expected number of random variables used by Algorithm 1 is . Algorithm 1 is exact.
For the situation of Example 2, with , equation (2) gives and we get the numerical values
| method | cost | |
| Algorithm 0, | 50 | 4.538% |
| Algorithm 0, | 65 | 0.951% |
| Algorithm 0, | 87 | 0.094% |
| Algorithm 1 | exact |
Table 1.
Thus, for the example the exact method will be faster than any useful version of Algorithm 0.
Applications
In this section we apply Algorithm 1 to three examples.
Random Factored Integers
For , a random integer is zeta-distributed, if it satisfies
for all , where is the Riemann zeta function. We can construct zeta-distributed values by sampling the prime factorisation of as follows: for every prime let be geometrically distributed with
for all , independently for different . Let
where the product is finite since, with probability one, only finitely many are non-zero. Then, if has prime factorisation , we find
Using the Euler product formula we get
and thus is zeta-distributed. This representation is classical: Golomb [16] shows that, for a zeta-distributed integer, divisibility by different primes is independent and that the exponent of each prime is geometrically distributed. A recent use of the representation is the ‘zeta process’ of Alexeev et al. [2], which couples the for different values of . Our aim here is to sample together with its prime factorisation, i.e. to sample the .
Sampling alone, without its factorisation, is a standard problem, and Devroye [11] gives a rejection method for the zeta distribution, which is called the Zipf distribution there. Recovering the factorisation afterwards requires factoring , and this is not feasible when is close to 1, because is then typically very large. Indeed, we have
and this expression behaves like as .
Alternatively, we could use Algorithm 0, sampling for all primes and setting for all primes . The result is wrong whenever a prime larger than divides , and we have
By the prime number theorem, the sum on the right-hand side decays only like as . In contrast to Example 2, where the corresponding probabilities decay geometrically, a small error probability thus requires a very large value of when is close to 1.
The corresponding problem for uniformly distributed integers was solved by Bach [4] and, with a simpler algorithm, by Kalai [17]. Both methods generate a random integer together with its prime factorisation, using primality tests in place of factorisation. Bodini and Lumbroso [6] construct samplers for distributions which are defined by Dirichlet series. Their samplers cover the zeta distribution without the factorisation as well as the distribution of a single random prime, but the multiset construction which would be needed for the prime factorisation is deferred to an extended version of their article. To our knowledge, this extended version has not yet appeared.
To apply Algorithm 1, we note that a prime divides if and only if . These events are independent, with
for all primes , and we have . Thus, the set of primes which divide is a random set of the kind considered in this article. Once this set is known, the exponents are easy to generate, since
for all is a geometric distribution.
The index set of the events is now the set of primes instead of , and there is no convenient probability distribution on the primes which we could use in Algorithm 1. We solve this problem by extending the index set: we set for all integers , whether prime or not, apply Algorithm 1 to this larger family of events and, at the end, discard all indices which are not prime. As a minor optimisation, we treat the prime 2 separately, by sampling directly, and then restrict the algorithm to the odd integers .
To choose the proposal distribution , let and, for , let be the set of all odd integers with . The sets are disjoint, each has elements, and every odd integer is contained in exactly one of the . We define
for all and all . Since the weights of the elements of sum to , this defines a probability distribution. To sample from , we can first generate with probabilities and then choose uniformly from , which requires random bits.
To find the constant , we again use the fact that the function from Example 2 is monotonically increasing on . For we have and , and thus
As we have , and thus behaves like where . Combining these choices with Algorithm 1, we obtain the following method, which we call the zeta sampler.
Zeta sampler. Let , , and be as above.
Generate with for all .
Generate .
For , independently, generate with for all , choose uniformly from , and generate uniformly distributed on .
Let be the set of all such that and is prime.
For every , generate with the probabilities given in (3). Set for all odd primes .
The output of the zeta sampler is the family of exponents, and thus the prime factorisation of .
In step 4, the condition should be checked first, so that the more expensive primality test is only needed for those candidates which satisfy this condition. By Lemma 2, the expected number of candidates is . A candidate equals and satisfies with probability , and thus the expected number of primality tests is
which behaves like as . The sum on the left-hand side is the constant from section 2.2 for the events with odd index . Since behaves like , the probability that a candidate is accepted converges to as . A candidate from has binary digits, and the expected number of digits is . Since the time needed to test an integer for primality is polynomial in the number of digits (Agrawal et al. [1]), the expected running time of the zeta sampler is bounded by a polynomial in . This matches the size of the output, since is also of order .
For comparison, we consider the cut-off which Algorithm 0 needs in order to achieve an error probability of 1%. By the prime number theorem we have
where is the exponential integral. The error probability equals 1% when the sum equals , and since , the required cut-off is , which grows exponentially in . We get the following numerical values.
| expected number of primality tests | expected number of binary digits | cut-off for Algorithm 0 | ||
| 1.5 | 1.34 | 0.72 | 4.4 | 601 |
| 1.1 | 8.27 | 4.74 | 15.9 | |
| 1.01 | 87.2 | 49.8 | 145.8 | |
| 1.001 | 876.9 | 499.8 | 1444.2 |
Table 1 (PDF p. 10).
The cut-off for was determined by direct computation, the other values of were obtained using the approximation above. For , for example, the zeta sampler tests on average 50 integers with about 146 binary digits each for primality, whereas Algorithm 0 would need to consider all primes up to .
We conclude this section with three remarks. First, the zeta sampler is exact only if the primality test in step 4 is. If a probabilistic method like the test of Rabin [21] is used instead, each composite candidate is accepted as a prime factor with a probability of less than , where is the number of rounds of the test. Second, the proposal distribution used here is not the only possible choice. For example, we could use the zeta distribution itself, conditioned on , as the proposal for all primes including 2. This corresponds to and leads to , which is larger than the value obtained above. Finally, the same method applies to related distributions. If we replace the by independent random variables with values in and , then is square-free with proportional to for all square-free . Since , we can use the same with . Step 1 changes accordingly, and step 5 is no longer needed. This is a multiplicative analogue of the powersets considered by Peyen [20].
Random Integer Partitions
As another application of Algorithm 1 we consider how to sample from the uniform distribution on all integer partitions of a given size. For an integer partition , we define
Since the order of the does not matter, each integer partition corresponds to a unique sequence . Let . As shown by Fristedt [14], choosing for all , independently, leads to a distribution of where all partitions of a given size have the same probability: for a fixed partition , corresponding to a sequence we have
Since
we can use Algorithm 1 to exactly simulate the set
as was demonstrated in Example 2. Then we have
for all and thus for all we can simply generate , independently. Finally, for all , we set .
To generate random partitions from the uniform distribution on all partitions of an integer , we can now first generate as described above, then take the corresponding , and finally condition on by rejecting all generated with .
While this method works for every , we can tune to make the final rejection step more efficient. The average weight of a partition generated by the algorithm is
This expression increases to infinity as . Setting we find
and for we can use Riemann approximation to get
Thus, for large , we can choose to get .
Similarly, the variance is given by
Since , we have
Let denote the expected number of attempts needed to obtain a partition with . Since the acceptance probability is of order , we have . The cost of each attempt is determined by the expected number of Poisson points. Since , we have
Thus the overall complexity of the rejection sampling algorithm is
The factor is caused by the geometric proposal distribution from Example 2. Using the Riemann approximation again, we find that the lower bound from § 2.2 satisfies
and thus the probability that a point is accepted is only of order . A proposal distribution for which is of the same order as would reduce the cost to order .
For comparison, Arratia and DeSalvo [3] represent each geometric random variable as a sum of independent Poisson random variables and generate all from a single Poisson process. This requires of order random numbers per attempt, which is the order of , so that the rejection method has cost of order , without the logarithmic factor, and their probabilistic divide-and-conquer method reduces the number of attempts further. For integer partitions, Algorithm 1 thus does not improve on the existing methods. We include the example because it is the simplest application of the algorithm.
Convex Polygonal Lines
A convex polygonal line is a path from the origin to some endpoint , with vertices in and consisting of segments with strictly increasing slope. As observed by Sinaï [22], such paths are in one-to-one correspondence with finitely supported functions , where
and gives the multiplicity of the side in direction .
For parameters , consider the family of independent random variables with geometric distributions, given by
for all and all . The path corresponding to has endpoint , and all paths with a given endpoint have the same probability: for a fixed with endpoint we have
which does not depend on except via the endpoint of the path.
Our aim is to sample from the random field using Algorithm 1. Because there is no simple closed form for the normalizing constant of a probability distribution supported on , it is difficult to apply the algorithm directly to the random field on . However, since the distribution factorizes as a product of geometric distributions on , we can first extend the random field from to , apply Algorithm 1 there, and then restrict the result back to , as we did for the primes in section 3.1.
As before, we use Algorithm 1 to determine which should be non-zero, and then sample each non-zero from the distribution given in (4), conditioned on . For this, let
Here we choose
for all . Since is the product of two geometric distributions, it is clear that is a probability distribution. Furthermore, we have
Since is monotonically increasing on and we find
Thus, we can apply Algorithm 1 with index set and discard all points with . By Lemma 2, the expected number of proposals is . The set also contains the two points and , which are not elements of . For these two points we sample and directly from the geometric distributions in (4).
To generate convex polygonal lines from the uniform distribution on all such lines with a given endpoint , we can proceed as for integer partitions in § 3.2. We first generate as described above, then take the corresponding path, and finally reject the path if it does not end at . Since all paths with the same endpoint have the same probability, the accepted path is uniformly distributed. This method works for all , but the final rejection step is more efficient if and are chosen so that the expected endpoint of the path is close to .
A note on the use of AI. The original draft, including Sections 2, 3.2 and 3.3, was written by the authors, before large language models existed. The application which is now Section 3.1 was suggested by AI (Anthropic’s Claude), and AI was also used to help with the literature review, to polish the presentation, and to write the Python script which in turn produced Figure 1.
References
- [1]M. Agrawal, N. Kayal, and N. Saxena. PRIMES is in P. Annals of Mathematics, 160 (2004), no. 2, 781–793. doi:10.4007/annals.2004.160.781DOI
- [2]B. Alexeev, K. Barreto, Y. Li, J. D. Lichtman, L. Price, J. I. Shah, Q. Tang, and T. Tao. Primitive sets and von Mangoldt chains: Erdős problem #1196 and beyond (2026). https://arxiv.org/abs/2605.00301
- [3]R. Arratia and S. DeSalvo. Probabilistic divide-and-conquer: A new exact simulation method, with integer partitions as an example. Combinatorics, Probability and Computing, 25 (2016), no. 3, 324–351. doi:10.1017/S0963548315000358DOI
- [4]E. Bach. How to generate factored random numbers. SIAM Journal on Computing, 17 (1988), no. 2, 179–193. doi:10.1137/0217012DOI
- [5]A. Beskos, O. Papaspiliopoulos, and G. O. Roberts. Retrospective exact simulation of diffusion sample paths with applications. Bernoulli, 12 (2006), no. 6, 1077–1098. doi:10.3150/bj/1165269151DOI
- [6]O. Bodini and J. Lumbroso. Dirichlet random samplers for multiplicative structures. In 2012 Proceedings of the Ninth Workshop on Analytic Algorithmics and Combinatorics (ANALCO). Society for Industrial and Applied Mathematics (2012) pp. 92–106. doi:10.1137/1.9781611973020.12DOI
- [7]L. V. Bogachev. Unified derivation of the limit shape for multiplicative ensembles of random integer partitions with equiweighted parts. Random Structures & Algorithms, 47 (2015), no. 2, 227–266. doi:10.1002/rsa.20540DOI
- [8]L. V. Bogachev, A. V. Gnedin, and Y. V. Yakubovich. On the variance of the number of occupied boxes. Advances in Applied Mathematics, 40 (2008), no. 4, 401–432. doi:10.1016/j.aam.2007.05.002DOI
- [9]L. V. Bogachev and S. M. Zarbaliev. Universality of the limit shape of convex lattice polygonal lines. The Annals of Probability, 39 (2011), no. 6, 2271–2317. doi:10.1214/10-AOP607DOI
- [10]S. DeSalvo. Improvements to exact Boltzmann sampling using probabilistic divide-and-conquer and the recursive method. Pure Mathematics and Applications, 26 (2017), no. 1, 22–45. doi:10.1515/puma-2015-0020DOI
- [11]L. Devroye. Non-uniform random variate generation. Springer-Verlag, New York (1986). doi:10.1007/978-1-4613-8643-8DOI
- [12]P. Duchon, P. Flajolet, G. Louchard, and G. Schaeffer. Boltzmann samplers for the random generation of combinatorial structures. Combinatorics, Probability and Computing, 13 (2004), no. 4-5, 577–625. doi:10.1017/S0963548304006315DOI
- [13]P. Flajolet, É. Fusy, and C. Pivoteau. Boltzmann sampling of unlabelled structures. In Proceedings of the Fourth Workshop on Analytic Algorithmics and Combinatorics (ANALCO). Society for Industrial and Applied Mathematics (2007) pp. 201–211. doi:10.1137/1.9781611972979.5DOI
- [14]B. Fristedt. The structure of random partitions of large integers. Transactions of the American Mathematical Society, 337 (1993), no. 2, 703–735. doi:10.1090/S0002-9947-1993-1094553-1DOI
- [15]A. Gnedin, B. Hansen, and J. Pitman. Notes on the occupancy problem with infinitely many boxes: general asymptotics and power laws. Probability Surveys, 4 (2007), 146–171. doi:10.1214/07-PS092DOI
- [16]S. W. Golomb. A class of probability distributions on the integers. Journal of Number Theory, 2 (1970), no. 2, 189–192. doi:10.1016/0022-314X(70)90018-1DOI
- [17]A. Kalai. Generating random factored numbers, easily. Journal of Cryptology, 16 (2003), no. 4, 287–289. doi:10.1007/s00145-003-0051-5DOI
- [18]J. F. C. Kingman. Poisson processes, volume 3 of Oxford Studies in Probability. Clarendon Press (1993).DOI
- [19]P. A. W. Lewis and G. S. Shedler. Simulation of nonhomogeneous Poisson processes by thinning. Naval Research Logistics Quarterly, 26 (1979), no. 3, 403–413. doi:10.1002/nav.3800260304DOI
- [20]J. C. Peyen. Oracle-free Boltzmann sampling for powersets (2026). https://arxiv.org/abs/2601.09508
- [21]M. O. Rabin. Probabilistic algorithm for testing primality. Journal of Number Theory, 12 (1980), no. 1, 128–138. doi:10.1016/0022-314x(80)90084-0DOI
- [22]Y. G. Sinaï. Probabilistic approach to the analysis of statistics for convex polygonal lines. Functional Analysis and its Applications, 28 (1994), no. 2, 108–113. Russian original: Funktsional. Anal. i Prilozhen. 28 (1994), no. 2, 41–48. doi:10.1007/BF01076497DOI
- [23]A. M. Vershik. Statistical mechanics of combinatorial partitions, and their limit shapes. Functional Analysis and its Applications, 30 (1996), no. 2, 90–105. Russian original: Funktsional. Anal. i Prilozhen. 30 (1996), no. 2, 19–39. doi:10.1007/BF02509449DOI
