Home  >  Article  >  Backend Development  >  How to Generate Random Numbers with a Fixed Sum, Guaranteed Uniform Distribution?

How to Generate Random Numbers with a Fixed Sum, Guaranteed Uniform Distribution?

Susan Sarandon
Susan SarandonOriginal
2024-10-27 10:50:30764browse

How to Generate Random Numbers with a Fixed Sum, Guaranteed Uniform Distribution?

Generating Random Numbers with a Fixed Sum

The challenge posed is to generate a series of pseudo-random numbers whose sum equals a predefined value. Specifically, how to generate four numbers that, when added together, equal 40.

Instead of relying on a method that could bias the distribution of the first number, a more uniform approach is employed. The solution utilizes a strategy of dividing the predefined value into smaller segments, using randomly selected dividers.

Assume we have four random positive integers (e, f, g, and h) such that 0 < e < f < g < h < 40. We can derive the desired four numbers as:

a = e
b = f - e
c = g - f
d = 40 - g

This technique guarantees an equal probability for each set of numbers, ensuring a uniform distribution. The resulting random numbers meet the requirement of summing to the predefined value.

Extending this concept, the following Python function generates a random list of positive integers summing to a specified total:

<code class="python">import random

def constrained_sum_sample_pos(n, total):
    """Return a randomly chosen list of n positive integers summing to total.
    Each such list is equally likely to occur."""

    dividers = sorted(random.sample(range(1, total), n - 1))
    return [a - b for a, b in zip(dividers + [total], [0] + dividers)]</code>

To generate non-negative integers, an additional transformation is employed:

<code class="python">def constrained_sum_sample_nonneg(n, total):
    """Return a randomly chosen list of n nonnegative integers summing to total.
    Each such list is equally likely to occur."""

    return [x - 1 for x in constrained_sum_sample_pos(n, total + n)]</code>

The above is the detailed content of How to Generate Random Numbers with a Fixed Sum, Guaranteed Uniform Distribution?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn