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?

1
  • 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. Commented Nov 26, 2018 at 11:12

3 Answers 3

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

0

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

1 Comment

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)) ``

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.