จำกัดช่วงของเลขสุ่มใน Stan

ถ้าจะจำกัดช่วงของเลขที่สุ่มจาก distribution ใดๆสามารถที่จะช่วงที่ต้องการได้โดยใช้ truncation function T ตามนี้ อย่างเช่น ถ้าอยากให้ y สุ่มมาจาก normal ที่ค่าอยู่ในช่วง -0.2 ถึง 1.5 สามารถพิมพ์ได้ตามนี้ครับ

y ~ normal(0,1) T[-0.2,1.5];

หรือจะพิมพ์แบบนี้ก็ได้ครับ

y ~ normal(0,1);
if (y < -0.2 || y > 1.5)
   target += negative_infinity();
else
   target += -log_diff_exp(normal_lcdf(1.5|0,1),normal_lcdf(-0.2|0,1));

แต่ถ้าทำในภาษา Wolfram ก็พิมพ์แบบนี้ได้ครับ

DT = TruncatedDistribution[{-0.2, 1.5}, NormalDistribution[0, 1]]

ls = RandomVariate[DT, 100000];
Histogram[ls]
%d bloggers like this: