0

In python, I am trying to create a program that generates random numbers:

from random import *
x = 10
for i in range(x):
    print(randint(0, 100))

This program generates 10 random numbers between 0 and 100, like so:

81
92
86
26
78
85
28
32
79
20

But as you can see, this does not match my title. I want all these values to add up to 100. Is there anyway I can do this? Here is an example of what I would like:

11
13
42
4
5
2
3
10
5
5

(These are all randomised numbers, in this instance)

To summarise: Is there anyway to generate a set of random numbers that all sum up to one value?

jakethefake
  • 338
  • 1
  • 3
  • 14
  • 1
    Could you just generate 9 values and then do 100 (or whatever other value) - the sum of what's left? To make sure you don't preemptively go over, you could progressively reduce the maximum number as you loop – 10762409 Aug 19 '19 at 18:50
  • What sort of distribution do you need in your "random numbers"? Your lack of specificity makes this a trivial problem to solve. Depending on the specification, it could get tricky. – Prune Aug 19 '19 at 18:53

2 Answers2

0
import random

reqd_sum = 100
x = 10
for _ in range(x-1):
    num = random.randint(0, reqd_sum)
    reqd_sum -= num
    print(num)
print(reqd_sum)
Prasad
  • 5,946
  • 3
  • 30
  • 36
0

One possible solution:

from random import random

x = 10

values = [random() for i in range(x)]
s = sum(values)
values = [int((i / s) * 100) for i in values]
values[-1] += 100 - sum(values) # add the remainder to 100

print('Values :', values)
print('Sum    :', sum(values))

Prints (for example):

Values : [4, 14, 5, 8, 14, 20, 6, 13, 12, 4]
Sum    : 100
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91