Random number generation

I am very new with Rstudio, trying to learn..
Do you have any suggestions on how I can solve examples like this?

Write a function that generates n independent random variables from this:

Begin with

help(GammaDist)

if \Gamma means the gamma distribution

Usually you would calculate the cumulative density function and then use this to convert uniform random numbers to your chosen distribution.

However, I don't think you can analytically integrate this pdf.

The other method is to draw random points from the x-y box surrounding the pdf, and reject the ones that are above the pdf. However this is tricky since your limits are +/- infinity. But you could do it with a smaller x range if you knew the x value at which the pdf essentially goes to 0. Like this.

# plot the pdf
xlim <- 2 # by trial and error -2, 2 contains most of the curve
pdfx <- seq(-xlim, xlim, 0.001) 
pdfy <- 2^0.25*gamma(0.75)/pi*exp(-pdfx^4/2)
plot(pdfx, pdfy)

# generate enough points 
n <- 1000
x <- (runif(n*2)*2-1)*xlim # twice as many is enough
y <- runif(n*2)*max(pdfy)
myy <- 2^0.25*gamma(0.75)/pi*exp(-x^4/2) # calc pdf at x
i <- which(y < myy)[1:n] # find first n pairs which are valid
points(x[i], y[i]) # plot them

Created on 2020-11-09 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

is it not possible to make an invers function?

@technocrat it's a gamma function not a gamma distribution.

1 Like

Well \Gamma it! (Thanks.)

1 Like

I don't think so. You need to integrate it and then invert it. It's not possible for exp(-x^2).

https://www.quora.com/What-is-the-integral-of-e-x-4