2

Following this post, I can generate random integers with a fixed sum. However, I want to avoid any duplicate numbers (such as 20 in the following example):

import numpy as np

_sum = 100
n = 5
rnd_array = np.random.multinomial(_sum, np.ones(n)/n, size=1)[0]
rnd_array

>>> array([20, 24, 20, 21, 15])

How could I achieve this?

DavidG
  • 24,279
  • 14
  • 89
  • 82
Joseph
  • 586
  • 1
  • 13
  • 32
  • The answer is in this link. This question has been answered I guess https://stackoverflow.com/questions/22842289/generate-n-unique-random-numbers-within-a-range – Althaf1467 Jan 22 '19 at 11:42
  • @Althaf1467 - In terms of generating random numbers then yes, the post you linked to solves that. But I also want the random values to sum up to a specific value at the same time. – Joseph Jan 22 '19 at 12:19

1 Answers1

4

random.sample returns a list of unique values (see the docs.) It's called like this:

sample = random.sample(range(100), 5)

Edit: For using this to get fixed sum, I suggest reading this thread where the important code is:

from random import*
def f(n,s):
  r=min(s,1)
  x=uniform(max(0,r-(r-s/n)*2),r)
  return n<2and[s]or sample([x]+f(n-1,s-x),n)
Charles Landau
  • 4,187
  • 1
  • 8
  • 24
  • Your answer solves half the the problem :). The random values generated need to sum to a specific value (in my example, 5 random integers should sum to `100`). – Joseph Jan 22 '19 at 12:18
  • @Joseph I made an edit to show how `sample` is used in that context – Charles Landau Jan 22 '19 at 12:37
  • Thanks for the edit. The float values generated are indeed random and sum to 100. To get it to integer values which I needed, I used `x = int(uniform(max(0, r - (r - s/n) * 2), r))`. Thank you again :) – Joseph Jan 22 '19 at 13:03