Search code examples
rfunctionrandominversecdf

Inverse CDF method to simulate a random sample


I have a problem where I have written this piece of code, however I think there might be an issue with it.

This is the question: Write an R function called pr1 that simulates a random sample of size n from the distribution with the CDF which is given as..

F_X(x) = 0 for x<=10
     (x-10)^3/1000 for 10<x<20
    1 for x=>20

x = 10 ( 1 + u^(1/3)) #I have used the inverse CDF method here and I now want to simulate a random sample of size n from the distribution.

Here is my code:

 pr1 = function(n)

 { u = runif(n,0,1)
   x = 10 * ( 1 + u^(1/3))
   x }

 pr1(5)

#This was just to check an example with n=5

My question is, since the CDF is 10< x <20, will this affect my code in any way?

Thank you


Solution

  • Are you confusing the range of X with the sample size? The former is restricted to the range (10, 20), the latter can be any positive integer.

    You can do a sanity check on your inversion by considering U = 0, which should (and does) yield the minimum of the range of X, and U = 1, which should and does yield the maximum value of the range. There is no need to range restrict your inversion, the restriction is built into the use of U(0,1)'s on the input side, combined with the fact that CDFs are monotonically non-decreasing. Thus no value of U such that 0 < U < 1 can yield an outcome outside the range 10 < X < 20.