Generating Random Numbers Summing to a Predefined Value
In this context, we aim to generate a list of pseudo-random numbers that collectively add up to a specific predetermined value. One method involves randomly generating a number within a specified range, subtracting it from the total, and repeating this process until the sum equals the desired value. However, this approach favors the first generated number in terms of its contribution to the sum.
To ensure uniformity, a more sophisticated solution has been developed:
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)]
This method generates a list of positive integers that sum to the target value. The key concept is that every possible combination of numbers is equally likely to be generated. Additionally, extending this technique to different totals and varying numbers of random numbers is straightforward.
For instance, if we set n to 4 and total to 40, we might obtain the following output: [4, 4, 25, 7]. It's important to note that each element of this list, when summed, produces the predefined value of 40.
To allow for non-positive integers, a modification is available:
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)]
By incrementing each value by one, we can generate a list of non-negative integers that add up to the desired total.
This method ensures that every possible combination, regardless of whether the numbers are positive or non-negative, has an equal probability of being generated. With its user-friendly implementation and versatility across different scenarios, constrained_sum_sample_pos and constrained_sum_sample_nonneg have become integral to random number generation tasks in Python.
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