How to calculate mean (Expected Value) of a custom continuous distribution from the probability density in R

238 Views Asked by At

The probability density and the calculation for the mean "by hand" are given below: enter image description here

I have coded the probability density function as:

myfunc <- function(x){
  ifelse(x >= 0 & x < 0.5, 1,
         ifelse (x >= 0.5 & x < 1, 0.2,
                 ifelse(x >= 1 & x < 2, 0.8*(x-1), 0)))
}

I understand that the EV is the weighted integral but I am struggling to code the calculation.

Also, additionally: how could I simulate this (0.867) result over the long run?

Could someone help, please?

2

There are 2 best solutions below

3
one On BEST ANSWER

Here is one solution with integrate:

integrate(function(x) x*myfunc(x),lower=0,upper=2)

0.866666666666667 with absolute error < 9.6e-15
3
ThomasIsCoding On

I think the integrate approach by one is definitely the best to give you the analytical result.

If you are interested in a Monte Carlo simulation approach (you used the word "simulate" in your question), you can try something like below

> n <- 1e7

> x <- runif(n, 0, 2)

> y <- runif(n, 0, 2)

> 4 * mean(y <= x * myfunc(x))
[1] 0.8666928

The point is that you need have sufficiently large number n to approach the analytical mean value.


The idea of simulation is calculating the area portion under the curve x*myfunc(x)

ff <- \(v) v * myfunc(v)
curve(ff, 0, 2)

enter image description here