RNG for truncated distributions

For concreteness, I’ll give the example I worked on this morning. I want to draw from a left-truncated Weibull to impute right-censored event times. Let’s say that I want a Weibull(alpha, sigma) truncated so that my random draws are never below some lower boundary t.

Then I should:
(1) Figure out the quantile corresponding to lower cutoff t. Let’s say it’s 0.2, or the 20th percentile. Call that p.
(2) Draw from a continuous uniform(0.2, 1). Call that draw u.
(3) Apply the inverse transform for the cdf, or “percent point” function. I did not feel like doing algebra on a Monday morning so I found mine at https://www.wolframalpha.com/input/?i=inverse+cdf+weibull. This will return a draw from the correct truncated weibull.

(The unstated step 4 is to post on the Stan discourse to check my logic. So far the draws look good when I plot them, but I have not checked it much beyond that.)

For a double truncation, you would add a step to calculate the cdf at the upper truncation point and draw from a uniform(p1, p2) instead of uniform(p, 1).

functions {
  real tweibull_rng(real alpha, real sigma, real t) {
    real p;
    real u;
    real x;
    p = weibull_cdf(t, alpha, sigma);
    u = uniform_rng(p, 1);
    x = sigma * (-log1m(u))^(1/alpha);
    return x;
  }
}

9 Likes