Skip to content Skip to sidebar Skip to footer

How To Calculate Probability Of A Binary Function In Python?

Let us consider the following function: $f(x)=\begin{cases} 0,& \Pr(f(x)=0)=x \\ 1,& \Pr(f(x)=1)=1-x\end{cases}$, where $0< x< 1$ Trial: I have tried with th

Solution 1:

If you mean to say "0 with the probability of x, and 1 with the probability of 1 - x", random.random returns a random number from [0, 1), so you just check if x is greater than that number:

import random

def f(x):
    return x >= random.random()

Currently, your function returns 0 and 1 with a 50/50 chance.

Solution 2:

Yes, your code does the correct solution (based on the binomial distribution you've created calling N times f(x) ).

However, the probability of selecting 0 or 1 randomly from (0, 1) is 50/50, but, as you surely have noticed already, you're computing the probability for a given sample (Ex. [1, 1, 1, 1, 0]), not for the whole universe of calling infinite times f(x).

See: Binomial distribution.

You could write a more readable code if you store the results of the function in a list like this:

intents = []
num_intents = 1000for i in range(num_intents):
    intent.append(f(x))

Then:

print('pr(f(x)=0)={}'.format(intents.count(0)/num_intents)
print('pr(f(x)=1)={}'.format(intents.count(1)/num_intents)

I also recommend you to explore numpy and binomial distributions, numpy.random.binamial

Post a Comment for "How To Calculate Probability Of A Binary Function In Python?"