2
$\begingroup$

So, considering that $\theta = 2$ and density function is $f(x) = \theta x^{\theta - 1}, 0<x<1$ and $0$ anywhere else, how do I generate random data from this particular distribution? Here is the code I tried:

x <- rbeta(10000, 1, 2)                              
hist(x)                                                        
curve(dbeta(x, 1, 2), add = TRUE)

First, I don't know if I can generate the data using functon rbeta as my density function is not exactly like ordinary Beta distribution? Then, when I try to add theoretical distribution's curve, it doesn't appear at all in the region of the histogram, and if I plot it separately it is just a straight line nut a skewed curve like it should be. What am doing wrong?

$\endgroup$
6
$\begingroup$

To obtain the function $f(x) = \theta x^{\theta - 1}$ you need to use rbeta( , 2, 1), not rbeta( , 1, 2) (to see why look into ?rbeta).

density_fun <- function(x,theta=2){
  theta * x^(theta-1)
}

par(mfrow=c(1,2))
x <- rbeta(10000, 2, 1)                              
hist(x, freq=F, col="grey", border="white",main="rbeta(10000, 2, 1)", xlab="x", ylab="f(x)")              
curve(dbeta(x, 2, 1), add = TRUE,lwd=2)

x = seq(0, 1, length.out=500)
plot(x,density_fun(x),col="red", type="l",xlab="x", ylab="f(x)", main=expression(paste(f(x) == theta * x^(theta-1),", with ",theta==2)),lwd=2)

Result: enter image description here Note that you need to plot the histogram using the argument freq=F to plot bars on a probability density scale

As you can see, the function is indeed a straight line; it should not be a curve since for $\theta=2$ you have that $f(x) = 2 x^{2 - 1} = 2x$

| cite | improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you for the insightful reply, just wanted to ask, if I were to use the density_fun as an argument for a curve function, would that still be considered a theoretical density line, or is it better to use rbeta as it doesn't take into the consideration the density function given? I know this probably is dumb, but I just want to make sure. $\endgroup$ – use1883 Apr 9 at 17:03
  • $\begingroup$ In this case they are equivalent; density_fun is a proper density function since its integral (over the support [0,1]) is 1. $\endgroup$ – matteo Apr 10 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.