Reputation: 51
I'm trying to create a probability distribution using Numpy in the following way:
x = 3
pat = [0.20, 0.30, 1.30]
z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat)))
And this works fine. The problem is that my "population" is evolving and starts at 0, meaning that this may happen:
x = 3
pat = [0, 0, 0]
z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat)))
At which point, python is dividing by 0 and returns an error. Is there anyway to create a probability distribution of this kind?
Upvotes: 1
Views: 2598
Reputation: 1
Using python function to find the probability distribution where Sum(pijlog(pin) - sum(pi(log(pi) -sum(on(log(pj))
Upvotes: 0
Reputation: 27869
In one line it will look like this:
z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat))) if any(pat) else numpy.random.choice(x)
Upvotes: 2
Reputation: 6914
You can use simple if/else
for the edge case:
if sum(pat) != 0:
z = numpy.random.choice(x, p=numpy.ndarray.tolist(numpy.array(pat)/sum(pat)))
else:
z = numpy.random.choice(x)
Upvotes: 1