How to Generate Random Numbers that Sum to a Specific Value in Python?

Patricia Arquette
Release: 2024-10-27 20:47:30
Original
273 people have browsed it

How to Generate Random Numbers that Sum to a Specific Value in Python?

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>
Copy after login

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!