Generating Random Numbers Summing to a Predefined Value in Python
The challenge presented is to generate a set of pseudo-random numbers that collectively sum up to a specific value. Specifically, the user desires to generate four numbers that add up to 40.
Standard Solution
The standard solution is both uniform and adaptable to varying target sums. It employs random sampling to select a sequence of integers that satisfy the specified constraints:
<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>
Nonnegative Integer Solution
For situations where nonnegative integers are preferred, a simple transformation can be applied to the standard solution:
<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>
Graphical Explanation
To illustrate the generation process, consider the example of obtaining four positive integers summing to 10 using constrained_sum_sample_pos(4, 10).
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
Conclusion
The standard solution provides a reliable and uniform approach for generating random numbers with a predefined sum. It can be adapted for different sum values and extended to handle nonnegative integers.
The above is the detailed content of How to Generate Random Numbers that Sum to a Specific Value in Python?. For more information, please follow other related articles on the PHP Chinese website!