Sampling of mixed distribution

Hello, guys, could u please tell me how to do sampling of mixed distribution in stan?

for example: X and Y are two independent variables which follow any distribution i prefer. How can I do sampling of X+Y ? in some cases, I could write a closed form, e.g. X ~ normal (0,1) Y~normal(0,1) so X+Y ~ normal(0,2). but in most cases it’s impossible. What’s the general solution in stan? Thanks!

I think this is what you’re looking for:

parameters {
  real x;
  real y;
}

transformed parameters {
  real z = x + y;
}

model {
  x ~ normal(0, 1);
  y ~ normal(0, 1);
}

z is defined as x + y, so it’ll have the appropriate distribution. Also side note Stan parameterizes normal distributions with a mean and standard deviation, so normal(0, 1) + normal(0, 1) is distributed as normal(0, sqrt(2)) in Stan notation.

Hope that helps!

(p.s. you could have x and y distributed as whatever you want in the model above, doesn’t have to be normals)

thanks!

If you don’t need to use that z in the rest of the model, then you want to put it in generated quantities for efficiency:

generated quantities {
  real z = x + y;
}