# RNG for truncated distributions

**URL:** <https://discourse.mc-stan.org/t/rng-for-truncated-distributions/3122>\
**Category:** Modeling\
**Tags:** truncated, rng\
**Created:** [January 29, 2018, 10:54am UTC](https://discourse.mc-stan.org/t/rng-for-truncated-distributions/3122 "2018-01-29T10:54:28Z")\
**Posts on this page:** 1\
**Showing post:** 7

<div class="post-metadata">

**Author:** ![lcomm](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/lcomm/32/1238_2.png) [@lcomm](https://discourse.mc-stan.org/u/lcomm)\
**Post date:** [January 29, 2018, 5:39pm UTC](https://discourse.mc-stan.org/t/rng-for-truncated-distributions/3122/7 "2018-01-29T17:39:47Z")

</div>

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](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;
  }
}

```

---

_[View the full topic](https://discourse.mc-stan.org/t/rng-for-truncated-distributions/3122)._
