Uneven distributed random array

I need to create a vector of random floating-point numbers between [0,1] such that their sum is 1 and is distributed unevenly. Is there any python function that generates such a vector?

Best wishes

+4
source share
2 answers

The distribution you're probably looking for is called the Dirichlet distribution . Python has no built-in function for drawing random numbers from the Dirichlet distribution, but NumPy contains one:

>>> from numpy.random.mtrand import dirichlet >>> print dirichlet([1] * n) 

This will give you n numbers summing up to 1, and the probability of each such combination will be equal.

Alternatively, if you do not have NumPy, you can use the fact that a random sample taken from the n-dimensional Dirichlet distribution can be generated by drawing n independent samples from the gamma distribution with shape and scale parameters equal to 1, and then dividing the samples by the amount:

 >>> from random import gammavariate >>> def dirichlet(n): ... samples = [gammavariate(1, 1) for _ in xrange(n)] ... sum_samples = sum(samples) ... return [x/sum_samples for x in samples] 

The reason you need the Dirichlet distribution is because if you just randomly randomly produce random numbers from a certain interval and then divide them by the sum of them, the resulting distribution will be shifted to samples consisting of approximately equal numbers. See Luke Devoni's book for more information on this topic.

+16
source

B. The code below creates a sample of size k:

 params = [a1, a2, ..., ak] sample = [random.gammavariate(a,1) for a in params] sample = [v/sum(sample) for v in sample] 
+2
source

Source: https://habr.com/ru/post/1312646/


All Articles