1

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?

GWasp
  • 51
  • 6
  • replace numpy.ndarray.tolist(numpy.array(pat)/sum(pat)) with numpy.ndarray.tolist(numpy.array(pat)/sum(pat)+1e-9).It will make sure that denominator will not be zero but a very very small number. It won't change you answer and not give divide by zero error. – Anubhav Singh Nov 26 '18 at 11:12

3 Answers3

2

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)
zipa
  • 27,316
  • 6
  • 40
  • 58
1

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)
taras
  • 6,566
  • 10
  • 39
  • 50
0

Using python function to find the probability distribution where Sum(pijlog(pin) - sum(pi(log(pi) -sum(on(log(pj))

  • Please use code fences to display code as such. Thank you! Like this Using python function to find the probability distribution where `` Sum(pijlog(pin) - sum(pi(log(pi) -sum(on(log(pj)) `` – Mike_H Aug 28 '22 at 01:54