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?

2
  • The answer is in this link. This question has been answered I guess stackoverflow.com/questions/22842289/… Commented Jan 22, 2019 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. Commented Jan 22, 2019 at 12:19

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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 I made an edit to show how sample is used in that context
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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.