2

I'm trying to get a random distribution of N integers with total sum equal to K.

numbers = np.array(range(N))

for n in range(N):
    prob[n] = rd.randrange(10000)

sum = numpy.sum(prob)
prob = (prob / sum * K).astype(int)

The problem is that the result is not exactly equal to N because of float number approximation. For example N = 100 will yield a a total of about 95.

What is a pythonic solution to this problem?

maja
  • 697
  • 5
  • 18
  • What sort of distribution should the random numbers have? – Phrogz Jan 13 '18 at 19:06
  • 2
    How about: generate any random set of integers (of a size and distribution that you like) using your technique, and then adjust the last value to make the sum match? – Phrogz Jan 13 '18 at 19:09
  • @Phrogz any random distribution would work, what you suggest is not very elegant but doable – maja Jan 13 '18 at 19:10
  • *Any* random-dist? Returning zeros only with the last number=N is *any* fixed random-dist too. Without more specifics it's hard to reason about the task. I'm not that sure if the above is an answer for this task. – sascha Jan 13 '18 at 19:15
  • 1
    I agree with @Phrogz, but was puzzling over the question, how should the OP determine the count of randoms before fudging the final one? I guess it could be the desired total divided by the mean value - 1? That will result in a sets of uniform max size. – danh Jan 13 '18 at 19:16
  • @sasha I'm sorry, what I meant is that the probability function is not a strict requirement. – maja Jan 13 '18 at 19:21
  • 1
    See https://stackoverflow.com/questions/36824129/how-can-i-create-three-random-integers-which-sum-to-a-specific-value-python/36824282#36824282 – ayhan Jan 13 '18 at 19:31
  • Your `n`s and `N`s seem a bit confused here. (E.g., when you do (prob / sum * n), the value of `n` will be `N-1` from the previous loop.) How many random numbers do you have, and what total should they sum to? – Mark Dickinson Jan 13 '18 at 19:32
  • @Mark, corrected the code, thanks – maja Jan 13 '18 at 19:35
  • So you want exactly `N` integers adding to `N`? – Mark Dickinson Jan 13 '18 at 19:36
  • 1
    I think the comments here (and the pointers to possible dups that are more fully specified) should communicate to you that the question is under-constrained. – danh Jan 13 '18 at 19:36
  • @Mark, now it's correct @ danh the technique described in both mentioned questions is what I was looking for – maja Jan 13 '18 at 19:41
  • btw, I tried to answer to this question with a link to the already answered question to mark it as solved, but the answer was converted to comment for 'triviality'. I don't know how else to mark this as solved... – maja Jan 13 '18 at 22:39

0 Answers0