4
$\begingroup$

This may be a basic question.

Given an array of probabilities of length $n$, trying to create a vector of all $2^n$ combinations assuming independence between them, where either $p_i$ or $1-p_i$ is chosen in each combination.

Input (for $n=3$)

p={p1,p2,p3}

Output

out={p1*p2*p3,p1*p2*(1-p3),p1*(1-p2)*p3,p1*(1-p2)*(1-p3),(1-p1)*p2*p3,(1-p1)*p2*(1-p3),(1-p1)*(1-p2)*p3,(1-p1)*(1-p2)*(1-p3)}
$\endgroup$
2
  • 2
    $\begingroup$ The function Tuples is probably what you want: n = 3; out = # /. List -> Times & /@ Tuples[Table[{p[i], 1 - p[i]}, {i, n}]]. $\endgroup$
    – JimB
    Commented May 2, 2020 at 0:23
  • 2
    $\begingroup$ Or: pT = Transpose[{p, 1 - p}]; Flatten[Outer[Times, Sequence @@ pT]]. Some people despise Sequence. Me, I like him just fine. And mostly for the type of use shown here (converting a List to a, well, sequence). $\endgroup$ Commented May 2, 2020 at 16:09

3 Answers 3

5
$\begingroup$
ps=Times @@@ Tuples[Transpose[{#, 1 - #}]] &;

Usage example:

p={a,b,c,d}
ps@p

{a b c d,a b c (1-d),a b (1-c) d,a b (1-c) (1-d),a (1-b) c d,a (1-b) c (1-d),a (1-b) (1-c) d,a (1-b) (1-c) (1-d),(1-a) b c d,(1-a) b c (1-d),(1-a) b (1-c) d,(1-a) b (1-c) (1-d),(1-a) (1-b) c d,(1-a) (1-b) c (1-d),(1-a) (1-b) (1-c) d,(1-a) (1-b) (1-c) (1-d)}

$\endgroup$
1
  • $\begingroup$ @JimB - Thanks! $\endgroup$
    – ciao
    Commented May 3, 2020 at 4:13
4
$\begingroup$

Depending on how you want to define p:

p=.;
n = 3;
out = # /. List -> Times & /@ Tuples[Table[{p[i], 1 - p[i]}, {i, n}]]
(* {p[1] p[2] p[3], p[1] p[2] (1 - p[3]), p[1] (1 - p[2]) p[3], p[1] (1 - p[2]) (1 - p[3]), 
    (1 - p[1]) p[2] p[3], (1 - p[1]) p[2] (1 - p[3]), (1 - p[1]) (1 - p[2]) p[3],
    (1 - p[1]) (1 - p[2]) (1 - p[3])} *)

or

p=.;
n = 3;
p = Table[ToExpression["p" <> ToString[i]], {i, n}]
out = # /. List -> Times & /@ Tuples[Table[{p[[i]], 1 - p[[i]]}, {i, n}]] 
(* {p1 p2 p3, p1 p2 (1 - p3), p1 (1 - p2) p3, p1 (1 - p2) (1 - p3), (1 - p1) p2 p3,
   (1 - p1) p2 (1 - p3), (1 - p1) (1 - p2) p3, (1 - p1) (1 - p2) (1 - p3)} *)
$\endgroup$
2
$\begingroup$
probs = PDF[ProductDistribution @@ Map[BernoulliDistribution] @ #] /@ 
    Tuples[{1, 0}, Length@#] &;

probs[{a, b, c, d}] // Column

enter image description here

Also

bmterms = Table[BooleanMinterms[{i}, #], {i, 2^Length@# - 1, 0, -1}] /.
    {And -> Times, Not -> (1 - # &)} &;

bmterms[{a, b, c, d}] == probs[{a, b, c, d}]
True
$\endgroup$

Your Answer

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

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