Well, we could use distribution which outcome naturally sums to known value, and
with fixed number of sampled numbers mean would be fixed as well.
Mean of 5 and number of samples to be 15 means total sum of number shall be always equal to 75.
Simplest one is Multinomial, so lets use it from NumPy. We set equal probabilities to 1/15, sample in the range [0...30] and reject sampling if any values is above desired range.
It is faster than method proposed by @jbch, no manual balance of sums and means, and distribution histogram is closer to symmetric if you care about it
Code
import numpy as np
def multiSum(n, p, maxv):
while True:
v = np.random.multinomial(n, p, size=1)
q = v[0]
a, = np.where(q > maxv) # are there any values above max
if len(a) == 0: # accept only samples below or equal to maxv
return q
N = 15
p = np.full((N), 1.0/np.float64(N))
mean = 5
start = 3
stop = 7
n = N*mean - N*start
h = np.zeros((5), dtype=np.int64)
print(h)
for k in range(0, 10000):
ns = multiSum(n, p, stop-start) + start # result in [3...7]
#print(np.mean(ns))
for v in ns:
h[v-start] += 1
print(h)
Typical output histogram on my computer
[15698 38107 44584 33719 17892]
@jbch output histogram
[17239 39237 42188 28957 22379]