8
$\begingroup$

I am wondering if there is a way in Mathematica, a special function perhaps, which would return true or false based on a certain probability I give it. Like Prob[0.7] would return 1: 70% of the time and 0: 30% of the time. I could do something like this of course:

prob=10; (* 1% chance *)
val = RandomInteger[{1, 1000}];
If[val<= prob, True, False];

But this becomes slightly difficult when I need very specific probabilities like 0.21321312444. Or even variable probabilities which would come from a certain function returning different values every time step.

$\endgroup$
12
$\begingroup$
Clear[prob]

prob[p_, n : _Integer : 1] := RandomChoice[{p, 1 - p} -> {1, 0}, n]

Total[prob[0.21321312444, 10^5]]/10.^5.

(*  0.21322  *)
$\endgroup$
16
$\begingroup$

Using built-in statistical functions (Discrete Univariate Distributions).

sampleBernoulli[p_, n_] := RandomVariate[BernoulliDistribution[p], n]

Then

sampleBernoulli[.7, 10]
(* {1, 0, 1, 0, 0, 0, 1, 1, 1, 1} *)

Hope this helps.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.