You could use a hit and miss approach (often used in probability simulations to randomly choose elements which satisfy certain constraints). The performance is acceptable unless np is too close to 1. Here is a Python implementation, which should be easy enough to translate to other languages:
from random import random
def makeDist(n,p):
#assumes p*n > 1
miss = True
while miss:
x = [p]
rest = [random() for i in range(1,n)]
total = sum(rest)
rest = [x*(1-p)/total for x in rest]
if all(x < p for x in rest):
x.extend(rest)
miss = False #we have a hit!
return x
Typical output:
>>> dist = makeDist(6,0.2)
>>> dist
[0.2, 0.08986510724051082, 0.18690143846768711, 0.19758176720598397, 0.19299989610231708, 0.13265179098350102]
>>> max(dist)
0.2
>>> sum(dist)
1.0
>>> makeDist(3,0.35)
[0.35, 0.31154704906869274, 0.33845295093130723]
>>>
random
function returns values in interval [0; 1]. You can use a formulavalues[i] = expectedValue + 2 * p * (random() - 1);
- Mark ShevchenkoexpectedValue
in your comment ? And isp
really in the distribution ? - elnabomax(distribution)=p
I mean that the highest probability in the distribution must be equal top in [0;1[
- elnabo