Abstract
Lei proposed an algorithm Algorithm in 2023 to generate an exact discrete uniform distribution from an unknown biased Bernoulli source. The present paper does not claim a new extraction algorithm. Its contributions are analytical: first, we provide a Fourier-analytic proof of the uniformity mechanism based on roots of unity and coefficient extraction; second, we derive explicit acceptance-probability and expected-runtime bounds, with a rigorous treatment of composite moduli; third, we show how independent accepted digits yield a continuous limit through a base-n expansion and quantify the cost of finite-digit simulation.
1. Introduction
1.1. The Quest for Perfect Randomness in Imperfect Worlds
New theory and large experiments show that coin tossing is not perfectly fair in the strict physical sense. The dynamical model from [1] predicts a small precession in flight that makes the coin slightly more likely to land on the same face it started with. A large experiment led by the University of Amsterdam collected 350,757 flips and found the probability of landing on the starting face is about 50.8% with a 95% confidence interval of [0.506, 0.509], and this result closely matches the approximately 51% theoretical prediction while the overall heads versus tails frequencies remain symmetric with heads at roughly 50.0% and a 95% confidence interval of [0.498, 0.502]. No systematic bias exists toward heads or tails but a subtle starting-orientation effect does exist, meaning raw coin tossing is not ideal for those demanding exact fairness.
This mild but detectable bias shows the value of the method from [2] published in Electronic Communications in Probability in 2023. Even when the base bit source, which is the coin, has an unknown bias, one can generate exactly discrete-uniform random numbers without parameters and with proof. The algorithm uses n tosses to form the head count N and a rank-sum R and it outputs R mod n whenever ; it adds an independent random cyclic shift if the flips are independent but not identically distributed, and this process yields an exactly uniform value on . Even with a starting-orientation bias in physical tossing, this number-theoretic–probabilistic “uniformization” delivers strictly fair n-ary outcomes that are useful for instructional labs, low-cost randomness acquisition and any application that needs verifiable fairness.
1.2. Historical Context and Theoretical Foundations
The present problem is related to broader literature on extracting unbiased randomness from biased sources, beginning with von Neumann’s extractor [3] and including refinements by Elias [4], Knuth-Yao [5], and Peres [6]. These methods optimize different efficiency or source-assumption criteria.
The mathematical problem of making fair random bits from biased coins has a long history. It started with von Neumann’s important 1951 work [3]. For a coin with unknown bias p, von Neumann suggested a simple algorithm. Flip the coin twice. Use the first flip as the result if the outcomes are different. Discard the two flips and try again if they are the same. This simple process gets exactly one fair bit from two biased flips. It has a variable cost and the expected runtime is flips per output bit.
Dijkstra [7] extended this framework to prime numbers. He created an algorithm that generates a uniform distribution on p elements from p coin flips. This method uses the algebraic structure of cyclic groups and lexicographic ranking within orbits made by cyclic shifts. The primality of p ensures each orbit has exactly p distinct configurations and this allows uniform sampling.
Lei [2] simplified this method by using rank sums modulo p instead of complex orbit analysis, replacing the latter with a straightforward modular computation. His simplification laid the groundwork for generalizing the method to any integer n, using a number-theoretic approach that combines ideas from probability theory and algebra. Lei’s algorithm is distinctive in that it produces exact n-ary uniform variables directly from a Bernoulli source through a number-theoretic acceptance condition. Our contribution is to analyze this mechanism using Fourier coefficients and to quantify the acceptance cost.
1.3. Applications in Modern Data Science
The algorithm’s importance extends beyond theoretical interest to practical applications across modern data science:
Statistical computing: The generation of non-uniform deviates via inversion, acceptance-rejection, or MCMC fundamentally relies on a source of i.i.d. uniform draws. By supplying such draws from an arbitrarily biased Bernoulli stream, immunises these procedures against source-level imperfections. In particular, Metropolis-Hastings samplers require proposal steps with exact uniformity to preserve detailed balance; the proposed method provides a parameter-free guarantee that is otherwise difficult to achieve without knowledge of the physical bias.
Machine Learning and Randomized Algorithms:Modern machine learning uses more and more randomness. It uses randomness for initialization (neural network weights), regularization (dropout), and optimization (stochastic gradient descent). This algorithm has provable fairness. It makes sure that these random parts do not add unintended biases. Ensemble methods like random forests use bootstrap sampling and random feature selection. This algorithm ensures that each data point and feature is selected with equal probability.
Reinforcement Learning: In Reinforcement learning (RL) and bandit algorithms, exploration strategies such as -greedy or Thompson sampling algorithms need uniform sampling to explore state spaces and K-arms; see [8]. A biased generator can cause systematic under-exploration of some action trajectories. MCMC inference uses an acceptance ratio. This ratio needs to compare a computed likelihood with a uniform variable . The bias in u breaks the detailed balance condition. This means the chain converges to the wrong stationary distribution. We extend to the continuous domain (Section 5) to fix this verification gap.
Cryptography and Security: Cryptographic protocols need high-quality randomness for key generation, nonce creation and probabilistic encryption. Cryptographic applications usually need stronger security guarantees than physical coin tossing alone can provide. This algorithm gives a valuable post-processing step. It helps distill entropy from imperfect sources in randomness extractors [9].
A concrete use case is finite experimental randomization from a simple biased physical or hardware Bernoulli source. Suppose a laboratory device produces binary events with unknown but stable bias p, and the experiment requires exact assignment among n treatment arms. Estimating p and then correcting the source introduces calibration error, whereas gives an exact uniform n-ary output under the i.i.d. Bernoulli model. This is the regime in which the algorithm is preferable: exact finite-sample n-ary uniformization is required, the source bias is unknown, and cryptographic security is not the primary objective.
1.4. Contributions and Paper Overview
In summary, the contribution of this paper is as follows: (1) We provide a characteristic-function proof of Lei’s algorithm [2] using roots of unity and coefficient extraction. (2) We prove explicit acceptance-probability and expected-runtime bounds, including the composite-modulus case. (3) We use independent accepted digits to construct a continuous limit and quantify finite-digit runtime and approximation error.
The specific contributions are as follows:
- A Novel Characteristic Function Proof (Section 3): We use a rigorous analytic proof with Characteristic Functions, which are Fourier analysis on , instead of the combinatorial group-action proof from the original paper. This proof is more robust and directly links the number-theoretic condition to the vanishing of Fourier coefficients at non-zero frequencies.
- Complexity Analysis (Section 4): We establish rigorous bounds on the algorithm’s expected runtime. We show the expected number of coin flips is when n is prime and when n is composite. We find explicit constants with Euler’s totient function and give detailed asymptotic expansions using analytic number theory tools.
- Extension to Continuous Uniform Distribution (Section 5): We show can be used to generate continuous uniform random variables on with base-n expansion. We prove convergence with characteristic function arguments and give error bounds for practical use.
The paper is organized as follows: Section 2 formally presents and establishes notation. Section 3 provides the characteristic function proof of uniformity. Section 4 analyzes computational complexity with detailed asymptotic expansions. Section 5 extends this method to the generation of continuous uniform distributions. Section 6 concludes with discussion and future directions.
2. Preliminaries and Algorithm Formulation
We operate within a standard probability space . Let and .
2.1. Model and Sufficient Statistics
Assumption 1 (Bernoulli Source).
Let be a sequence of independent and identically distributed (i.i.d.) random variables taking values in . We denote the success probability by and the failure probability by . We assume is unknown.
We denote a sequence of n flips as a random vector .
The algorithm relies on two statistics of the sample : the Hamming weight (head count) and a weighted positional sum (rank sum).
Definition 1 (Head Count).
For a vector , the head count is defined as:
Definition 2 (Rank Sum).
The rank sum is defined as the sum of indices where heads occur:
Definition 3 (Coprimality).
Let denote the greatest common divisor of integers x and y. We say N and n are coprime if . The set of integers in coprime to n forms the multiplicative group of integers modulo n, denoted by . The size of this group is given by Euler’s totient function .
2.2. Algorithm
The core algorithm proposed in [2] is a rejection sampling procedure. It generates batches of size n and accepts a batch only if the head count N is coprime to the batch size n (see Algorithm 1).
| Algorithm 1. Discrete Uniform Generation |
| Require: Sequence of biased coin flips . Target size . |
| Ensure: Random variable Y uniformly distributed on . |
|
2.3. Illustrative Examples
Example 1 (: Connection to von Neumann’s Algorithm).
For , reduces to a variant of von Neumann’s original procedure. Consider all possible outcomes:
- : , , reject
- : , , reject
- : , , , output
- : , , , output
The algorithm accepts exactly when the two flips differ, producing outputs 0 for and 1 for , matching von Neumann’s procedure.
Example 2 (: Composite Case).
Consider and the outcome :
- Head count:
- , so reject
Now consider :
- Head count:
- , reject again
Finally, consider :
- Head count:
- , reject
These examples illustrate that many outcomes are rejected when n has multiple prime factors.
3. Characteristic Function Proof of Uniformity
The algorithm admits a natural algebraic interpretation. Consider the random variable where represents tails and represents heads. Then, the n flips correspond to a random vector in . The head count condition ensures that the sum generates the entire group , while the rank sum condition provides a linear combination that, under this coprimality condition, yields uniform distribution.
Theorem 1.
Let be identically distributed Bernoulli variables with the probability of success and the probability of failure . Let and . For any integer c such that , the conditional distribution of given is uniform on .
3.1. Refined Proof: Group Action Method
Proof.
Let be the sample space of outcomes . Consider the cyclic shift operator defined by
Since the random variables are i.i.d., the probability measure P on is invariant under T; that is, for all .
We examine the behavior of the statistics N and R under this transformation. The total count is invariant:
For the rank sum R, observing that indices shift by , we compute:
By induction, for any , the k-th iteration of the shift satisfies
Consider the set of outcomes for a fixed count c satisfying . The operator T partitions into disjoint orbits. For any , the orbit is .
Because , the map is a bijection on . Consequently, the set of values is exactly , which is a permutation of .
Since the measure is invariant under T, every element in a given orbit has equal probability. Thus, conditional on falling into a specific orbit, is uniform. Since is a disjoint union of such orbits, is uniform on . □
This algebraic perspective connects the algorithm to deeper number-theoretic structures and motivates the characteristic function approach developed. We now use roots of unity to characterize the discrete uniform distribution on the set .
Lemma 1.
Let Z be a random variable supported on and write
Let and define the discrete Fourier coefficients
Then the following are equivalent:
- 1.
- Z is uniformly distributed on .
- 2.
- and for all ; equivalently
Proof.
(1 ⇒ 2). If Z is uniform on , then for all k and
For this is 1. For we use the geometric series:
so . Because , the stated values of follow.
(2 ⇒ 1). Let , , and consider the discrete Fourier transform (DFT)
On the finite abelian group , the DFT is invertible with the inversion formula
which follows from the orthogonality of nth roots of unity:
Now apply (3) with the assumption and for :
Hence for all k, i.e., Z is uniform on . □
While the group-action proof is combinatorially elegant, the characteristic-function approach reveals directly how forces the Fourier coefficients to vanish. The argument proceeds as follows.
3.2. New Proof: Characteristic Function Method
Proof.
Let . To establish uniformity on , it suffices to show that the conditional characteristic function of R vanishes at all non-zero frequencies. Specifically, we must show that for all :
Since implies and , we have . Hence the conditional expectation is well-defined by
We analyze the numerator. Consider the joint characteristic function (CF) of , defined for as:
Since and for , the series converges absolutely and coefficient extraction is valid.
By independence, the expectation factors:
where and .
Let and . The sequence of exponents traverses the values , each repeated times. With , a primitive -th root of unity,
Therefore is a polynomial in . Consequently unless . If , then and ; since , . Hence , and the nonzero Fourier coefficients vanish. We have:
where the notation is the coefficient of the term in the series expansion of . Since
Given the hypothesis , c cannot be a multiple of unless . If , then , implying . Since is a divisor of n greater than 1, and , it follows that . Therefore, for all .
The conditional characteristic function is thus:
By the uniqueness of the CF, R is uniformly distributed on conditional on . □
4. Complexity Analysis of Algorithm
We analyze the sample complexity of Algorithm , defined as the expected number of coin flips required to generate a single output sample.
Theorem 2 (Expected Complexity).
Let be the success probability of the biased coin. Let be the random variable representing the total number of coin flips performed by Algorithm to generate one output in .
The expected number of flips satisfies the following asymptotic bound as :
Furthermore, if n is prime, the complexity is strictly linear:
Proof.
Algorithm operates in independent trials. In each trial, a batch of n coin flips is generated. Let be the sequence of outcomes in a single batch, and let be the number of heads. The batch is accepted if and only if .
Let denote the probability of acceptance in a single trial:
Since trials are independent, the number of trials M required to obtain a valid output follows a Geometric distribution with parameter . The total number of flips is . By the properties of the Geometric distribution (), the expected number of flips is:
Case 1: n is Prime
If n is prime, for all . The condition fails only if or .
For any fixed , the terms and decay exponentially to 0. Thus, .
Case 2: n is Composite (General Case)
We estimate for composite n. As , the distribution of the sum N modulo d approaches a uniform distribution on when d is any fixed divisor of n.
The probability that N is coprime to n behaves asymptotically like the density of integers coprime to n in the range and this density is given by Euler’s totient function ratio :
Thus, for fixed and sufficiently large n, . This is the only estimate needed for the complexity upper bound.
The relevant lemmas and proofs can be found in Appendix A. Substituting this into the expectation:
By Landau’s theorem (see Theorem 328 of [10]), , hence
The prime case remains sharper. If n is prime, the only rejected head counts are 0 and n, so
□
According to Theorem 2, when n is prime, the expected complexity of Algorithm achieves a strict linear bound . This implies that the algorithm’s acceptance probability is approximately (as derived from ), thereby achieving an optimal linear time cost for generating a single output.
For the composite case, our analysis using Fourier methods and number theory demonstrates that the acceptance probability satisfies , where is Euler’s totient function and is the divisor function. By leveraging the properties and , we establish the lower bound . This directly leads to the expected complexity bound of .
This refined analysis not only explains the root cause of the complexity difference between prime and composite cases but also rigorously demonstrates, through a proven lower bound on the acceptance probability, that the complexity for composite n is indeed tight.
Remark 1.
The appearance of has a simple interpretation. A batch is accepted precisely when its head count lies in a residue class coprime to n. Among the n residues modulo n, exactly are coprime to n. Thus is the ideal acceptance density. The Moebius–Fourier calculation quantifies the deviation of the binomial head-count distribution from this ideal residue density.
5. Continuous Complexity Analysis of Algorithm
Having established the strict uniformity of the algorithm through a purely analytic characteristic function proof and derived tight asymptotic bounds on its expected runtime, we proceed to extend the method to the continuous uniform distribution in this section. We utilize the discrete extraction method from Theorem 3 to construct a random variable U on the continuous interval .
Definition 4 (Base-n Digit Generator).
Let be a stream of i.i.d. Bernoulli trials. We parse into disjoint blocks of length n. For each block j, we compute the total sum and rank sum .
- If , we accept the block and output the digit .
- If , we discard the block.
Let be the sequence of successfully generated digits. By Theorem 3 and the independence of the blocks, is a sequence of i.i.d. variables uniformly distributed on .
Base-n expansions are not unique on the countable set of n-adic rationals, where a terminating expansion can also be written with an eventually all- tail. We adopt the canonical convention that excludes the eventually all- representation. The digit sequence generated by independent accepted A3 blocks is almost surely not eventually constant equal to , so the ambiguity has probability zero and does not affect the distributional conclusion.
Theorem 3 (Continuous Uniformity).
Let U be the random variable defined by the base-n expansion using the digits generated above:
Then U follows a continuous uniform distribution on , i.e., .
Proof.
We use the method of Characteristic Functions. The characteristic function of the target distribution is:
We must show that is equal to .
- Case 1: Characteristic Function of a Single Digit
Since is uniform on , its characteristic function is:
- Case 2: Characteristic Function of the Partial Sum
Let be the partial sum of the first M digits. Since the digits are independent, the characteristic function of the sum is the product of the characteristic functions of the individual terms. The k-th term is .
Substituting into the single digit formula:
The preceding calculation assumes because the displayed telescoping quotient contains in the denominator. The point is immediate: for every M, , and the characteristic function of also equals 1 at zero. We therefore define at by continuity. Hence the characteristic functions converge for all .
The product over to M telescopes:
- Case 3: Convergence to the Continuum
We take the limit as . Consider the denominator term . Using the Taylor expansion for small x:
Substituting this back into the expression for :
The limit matches . By the Lévy Continuity Theorem, converges in distribution to U, and U is uniformly distributed on . □
For finite-precision simulation, the generator outputs . Since each digit requires one accepted A3 block and each block has acceptance probability , the expected number of biased flips is . Hence the finite-precision runtime is for prime n and for general n. Under the canonical coupling with the infinite expansion, .
In fact, let be the i.i.d. digits generated by accepted A3 blocks. Define
Then and
The expected number of biased coin flips required to generate is
which is for prime n and for general n.
The algorithm does not require storing the entire block. During the scan of a block, N and can be updated incrementally. Computing by the Euclidean algorithm adds only logarithmic arithmetic overhead. Therefore the dominant cost remains the generation of Bernoulli trials, while the modular arithmetic and gcd check are standard low-order implementation costs.
6. Conclusions
This paper has provided a comprehensive theoretical treatment of Lei’s algorithm for extracting exact discrete uniform distributions from biased Bernoulli trials, and has extended its reach to continuous uniform generation. Three primary contributions were presented. First, in terms of algorithm validity verification, we abandon the traditional group-theoretic proof framework and propose a novel analytic proof based on characteristic functions and roots of unity. Second, regarding sample complexity analysis, we derive the first explicit asymptotic bounds for Algorithm by combining properties of the binomial distribution, Euler’s totient function , and classical results from analytic number theory. Third, in the extension to continuous uniform distributions, we construct a Base-n Digit Generator using the discrete uniform digits output by .
From a methodological standpoint, the characteristic-function perspective not only simplifies the proof but also suggests possible generalizations to other group structures. The complexity analysis, albeit asymptotic, confirms that the rejection penalty for composite moduli is mild—only a logarithmic factor—and is unlikely to hinder practical deployment.
Future research directions can focus on three aspects: first, optimizing the rejection sampling strategy to reduce the discard rate of composite n, especially for large n with multiple prime factors; second, extending the algorithm to non-i.i.d. Bernoulli sources (e.g., sources with weak dependence) while maintaining uniformity guarantees; third, exploring the application of in privacy-preserving machine learning, such as ensuring fairness in federated learning systems where local hardware biases may compromise global model equity.
Author Contributions
Conceptualization, M.Z. and X.L.; methodology, M.Z.; software, M.Z. and G.T.; validation, M.Z. and G.T.; formal analysis, M.Z. and G.T.; investigation, M.Z.; resources, M.Z.; data curation, M.Z. and G.T.; writing—original draft preparation, M.Z.; writing—review and editing, M.Z. and G.T.; visualization, NONE; supervision, X.L.; project administration, M.Z.; funding acquisition, NONE. All authors have read and agreed to the published version of the manuscript.
Funding
This research received no external funding.
Data Availability Statement
The original contributions presented in this study are included in the article. Further inquiries can be directed to the corresponding author.
Conflicts of Interest
The authors declare no conflicts of interest.
Appendix A
Definition A1 (Möbius function).
The Möbius function is defined by
Equivalently, if d is not square-free, and if d is square-free then , where denotes the number of distinct prime divisors of d.
Lemma A1 (Acceptance probability via Möbius inversion and Fourier bounds).
Let , and let Bin (n,p) with and . Define the acceptance probability
Let be the Möbius function, Euler’s totient, and the divisor-counting function. Then
In particular, for all sufficiently large n (depending on p),
Proof.
Step 1: Möbius inversion for the coprimality indicator.
For integers one has the standard identity
This identity is also valid for . It is important to note the handling of . Taking expectation with gives
Step 2: Exact Fourier formula for .
Fix . Let . By the discrete Fourier inversion on ,
Taking expectation yields
since for .
For ,
Using and the inequality for , we obtain for ,
hence
References
- Diaconis, P.; Holmes, S.; Montgomery, R. Dynamical bias in the coin toss. SIAM Rev. 2007, 49, 211–235. [Google Scholar] [CrossRef] [Scilit]
- Lei, X. Generating discrete uniform distribution from a biased coin using number-theoretic method. Electron. Commun. Probab. 2023, 28, 1–6. [Google Scholar] [CrossRef] [Scilit]
- von Neumann, J. Various techniques used in connection with random digits. Natl. Bur. Stand. Appl. Math. Ser. 1951, 12, 36–38. [Google Scholar]
- Elias, P. Universally acceptable information sources. IEEE Trans. Inf. Theory 1962, 8, 213–219. [Google Scholar]
- Knuth, D.E.; Yao, A.C. The complexity of nonuniform random number generation. In Proceedings of the 18th Annual Symposium on Foundations of Computer Science (FOCS 1976); IEEE: New York, NY, USA, 1976; pp. 323–333. [Google Scholar]
- Peres, Y. Iterating von Neumann’s procedure for extracting random bits. Ann. Stat. 1992, 20, 590–597. [Google Scholar] [CrossRef] [Scilit]
- Dijkstra, E.W. Making a fair roulette from a possibly biased coin. Inf. Process. Lett. 1990, 36, 193. [Google Scholar] [CrossRef] [Scilit]
- Zhou, P.; Wei, H.; Zhang, H. Selective Reviews of Bandit Problems in AI via a Statistical View. Mathematics 2025, 13, 665. [Google Scholar] [CrossRef] [Scilit]
- Li, X.; Ruan, F.; Wang, H.; Long, Q.; Su, W.J. A statistical framework of watermarks for large language models: Pivot, detection efficiency and optimal rules. Ann. Stat. 2025, 53, 322–351. [Google Scholar] [CrossRef] [Scilit] [PubMed]
- Hardy, G.H.; Wright, E.M. An Introduction to the Theory of Numbers; Oxford University Press: Oxford, UK, 1979. [Google Scholar]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content. |
© 2026 by the authors. Licensee MDPI, Basel, Switzerland. This article is an open access article distributed under the terms and conditions of the Creative Commons Attribution (CC BY) license.