The following p.d.f is given:
f(x)=2x/k^2, where 0 <= x <= k
Let k=10, I'm trying to simulate 100 times for this p.d.f, then print the first 5 results and find the mean for all 100 times results.
If you want to simulate with a uniform distribution between 0
and k
, then you can pass runif(n, min, max)
into your pdf.
f <- function(x, k) {
return(2*x/k^2)
}
k <- 10
res <- f(runif(100, 0, k), k)
print(res[1:5])
print(mean(res))
Per MrFlick's comments, if you were instead wanting to do inverse transform sampling, this should suffice.
pdf <- function(x, k) {
return(2*x/k^2)
}
cdf <- function(x, k){
return(x^2/k^2)
}
icdf <- function(y, k){
return(sqrt(k^2*y))
}
k <- 10
res <- icdf(runif(100,0,1), k)
print(res[1:5])
print(mean(res))