"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to generate random numbers with fixed sums to ensure uniform distribution?

How to generate random numbers with fixed sums to ensure uniform distribution?

Posted on 2025-04-19
Browse:553

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

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:

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)]

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

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)]
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3