I want to generate a random variable $X$ with the pdf $f(x) = \Bigg\{ f_1(x)$ if $x < 1$ and $f_2(x)$ if $x > 1$.
As an example, $f_1(x)$ is ($x^{\alpha-1}$) where $0 < \alpha < 1$ and $f_2(x)$ is exp($\lambda$).
How should I do it, assuming I know how to generate Uniform $(0,1)$ ?
- 332
-
Ok. So what help would you like from us? – Mathemagical Sep 14 '17 at 11:31
-
Does your $f(x)$ integrate to 1? – kimchi lover Sep 14 '17 at 12:08
-
@kimchilover yes I can add suitable constants, and then $f(x)$ will integrate to 1. – Apurv Anand Sep 14 '17 at 12:19
-
@Mathemagical I don't know how to do it. I guess I could use inverse method. But I don't know exactly how to go about it. – Apurv Anand Sep 14 '17 at 12:21
2 Answers
Hint :
Find the inverse of the CDFs in each range and feed rand() into the inverse function of the CDF. For example
Let $X$ be $exp(a)$
$F(x) = 1-exp(\frac{x}{a}), x>0\tag{1}$
$ = 0 , otherwise$
Solving $u = F(x)$, you get $x = F_{-1}(u) = -aln(1-u)\tag{2}$
Generate $u$ rvs from $U(0,1)$, then apply the above equation (2) obtain $X$ having the CDF in (1)
In your example:
$F(x) = \int_{0}^{x}f_{1}(x), x<1$ where $f_{1}(x) = x^{\alpha-1}$
$F(x) = \int_{0}^{1}f_{1}(x)+ \int_{1}^{x}f_{2}(x), x>1$ where $f_{2}(x) = \lambda e^{-\lambda x}$
For $x\le 1$
$F(x) = \frac{x^{\alpha}} {\alpha - 1}$
And thus $x = e^{\left[\frac{ln(\alpha-1)}{\alpha} + \frac{ln(u)}{\alpha}\right]}$
For $x\gt 1$
$F(x) = \frac{1}{\alpha-1}+e^{-\lambda}-e^{-\lambda x}$
$u = \frac{1}{\alpha-1}+e^{-\lambda}-e^{-\lambda x}$
$x = -\frac{1}{\lambda}ln\left(\frac{1}{\alpha-1}+e^{-\lambda} - u\right)$
Generate $u$ rvs from $U(0,1)$, then apply the above equation obtain $X$ having the above CDF
- 11,984
A different approach. Assuming the integral of $f$ is $1$. Let $p=\int_{-\infty}^1 f(x)dx$, flip a biased coin for which the probability of heads is $p$. If the coin shows heads, repeatedly draw samples $x\sim f_1$ until $x<1$. If the coin shows tails repeatedly draw samples $x\sim f_2$ until $x>1$. The final value of $x$ will have the correct distribution.
Why this works: the final value of $x$ will obey $x\le 1$ with probability $p$, and $x>1$ with probability $1-p$, which is certainly correct. Now suppose $x\sim f, x_1\sim f_1, \text{ and } x_2\sim f_2$. The distribution of $x$ conditional on $x< 1$ is the same as that of $x_1$ conditional on $x_1< 1$, similarly the distribution of $x$ conditional on $x>1$ is the same as that of $x_2$ conditional on $x_2>1$. The business of repeated draws from $x\sim f_1$ until $x< 1$ is a way of generating a sample from $f_1$ conditional on $x<1$, and so on.
There might be situations where this is practical, when say the cdfs are too complicated to evaluate or invert numerically.
- 24,277
-
Could you also explain how x generated this way has pdf $f(x)$? Thanks in advance. – Apurv Anand Sep 14 '17 at 17:39
-