问题
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 the following code but I,m not sure whether it is correct or not. The codes are here:
import random
def f(x):
b=random.randint(0,1)
return b
x=0.3
count0=0
count1=0
for i in range(1000):
if f(x)==0:
count0=count0+1
else:
count1=count1+1
print 'pr(f(x)=0)=', count0*1.0/1000
print 'pr(f(x)=1)=', count1*1.0/1000
Does my code give the correct calculation? Please help?
回答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.
回答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 = 1000
for 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
来源:https://stackoverflow.com/questions/44571472/how-to-calculate-probability-of-a-binary-function-in-python