Home > Article > Backend Development > How to Generate Random Numbers with a Predefined Sum and Ensure an Equal Probability Distribution?
Generating random numbers to sum up to a predetermined value poses an interesting challenge in computer programming. While simple approaches may seem sufficient, they often introduce biases, where certain numbers have a higher likelihood of being selected. This article delves into a refined solution that ensures equal probability distribution for all possible combinations.
The provided solution relies on the constrained_sum_sample_pos function to achieve a uniform distribution of possible outcomes. This function generates a list of positive integers(n) that sum up to the target value(total). Its key feature is that each combination has an equal chance of being chosen.
The function's strength lies in its mathematical foundation, which guarantees that all possible combinations are equally likely. Additionally, it is easily adaptable to other scenarios, such as generating seven numbers summing up to 100 or any other desired total.
The Python implementation of the function is provided below:
<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>
@FM's graphical representation provides a clear understanding of the function's working:
0 1 2 3 4 5 6 7 8 9 10 # The universe. | | # Place fixed dividers at 0, 10. | | | | | # Add 4 - 1 randomly chosen dividers in [1, 9] a b c d # Compute the 4 differences: 2 3 4 1
This sophisticated solution, based on constrained sum sampling, provides a robust and unbiased method for generating random numbers that sum up to a predefined value. It ensures equal probability for all possible outcomes, making it a reliable tool for various programming scenarios.
The above is the detailed content of How to Generate Random Numbers with a Predefined Sum and Ensure an Equal Probability Distribution?. For more information, please follow other related articles on the PHP Chinese website!