Skip to main content
1 of 5
ciao
  • 26k
  • 2
  • 62
  • 145

When are `If`, `Piecewise`, `Switch`, and `Which` interchangeable and when are they not?

Experimenting with joint dependent distributions via the TransformedDistribution function, I used the following to derive a distribution where the second variate is distributed dependent on the value of the first variate (very simplified & contrived example follows).

distA = TransformedDistribution[{b, If[b == 1, d1, d2]}, {b \[Distributed] DiscreteUniformDistribution[{1, 2}], d1 \[Distributed] UniformDistribution[{1, 2}], d2 \[Distributed] UniformDistribution[{2, 3}]}] distB = TransformedDistribution[{b, Piecewise[{{d1, b == 1}, {d2, b == 2}}]}, {b \[Distributed] DiscreteUniformDistribution[{1, 2}], d1 \[Distributed] UniformDistribution[{1, 2}], d2 \[Distributed] UniformDistribution[{2, 3}]}] distC = TransformedDistribution[{b, Switch[b, 1, d1, 2, d2]}, {b \[Distributed] DiscreteUniformDistribution[{1, 2}], d1 \[Distributed] UniformDistribution[{1, 2}], d2 \[Distributed] UniformDistribution[{2, 3}]}] distD = TransformedDistribution[{b, Which[b == 1, d1, b == 2, d2]}, {b \[Distributed] DiscreteUniformDistribution[{1, 2}], d1 \[Distributed] UniformDistribution[{1, 2}], d2 \[Distributed] UniformDistribution[{2, 3}]}] 

The first two behave as I'd expect: Mean, Var, RandomVariate all do what they're supposed to. The latter two, while behaving as expected for the simple probability functions (e.g. Mean), puke on any attempt to sample with RandomVariate, with the message

TransformedDistribution::nnbprm: The valid numeric parameters of distribution TransformedDistribution[{\[FormalX]1,Switch[\[FormalX]1, 1,\[FormalX]2, 2,\[FormalX]3]},{\[FormalX]1,\[FormalX]2,\[FormalX]3}\[Distributed]ProductDistribution[DiscreteUniformDistribution[{1,2}],UniformDistribution[{1,2}],UniformDistribution[{2,3}]]] are expected. Use DistributionParameterAssumptions to obtain the parameter assumptions. >> 

I'm a bit puzzled by this, seems the forms in this case should result in equivalent behavior. Any insights?

ciao
  • 26k
  • 2
  • 62
  • 145