使用蒙特卡罗模拟计算方差的期望值 [英] Calculate expected value of variance using monte carlo simulation

查看:61
本文介绍了使用蒙特卡罗模拟计算方差的期望值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个概率分布

X = {0 概率 7/8}
{1/60 概率 1/8}

X = {0      probability 7/8}
      {1/60 probability 1/8}

James 他的车一年出故障 N 次,其中 N ~ Pois(2) 和 X 是修理成本,Y 是 James 在一年内造成的总成本.

James his car breaks down N times a year where N ~ Pois(2) and X the repair cost and Y is the total cost caused by James in a year.

我想计算 E[Y] 和 V(Y),这应该给我 E[X]=15 和 V(Y) = 1800

I want to calculate the E[Y] and V(Y), which should give me E[X]=15 and V(Y) = 1800

我有这个蒙特卡罗模拟:

I have this monte Carlo simulation:

expon_dis <- rexp(200, 1/60)

result_matrix2 <- rep(0, 200)
expected_matrix <- rep(0, runs)

for (u in 1:runs){
  expon_dis <- rexp(200, 1/60)
  N <- rpois(200, 2)
  for (l in 1:200){
    result_matrix2[l] <- (expon_dis[l] * (1/8)) * (N[l])
  }
  expected_matrix[u] <- mean(result_matrix2)
}

此代码给出的预期值为 15,但方差不正确.那么这个模拟有什么问题?

This code gives the expected value of 15 but the variance is not correct. So what is wrong with this simulation?

推荐答案

没有足够的时间通读您的代码,但我认为乘法会出现错误.

Not enough time to read through your code, but i think the error comes with the multiplication.

下面是一个非常粗略的实现,首先你编写一个函数来模拟成本,给定 x 次故障:

Below is a very rough implementation, where first you write a function to simulate the cost, given x number of breakdowns:

sim_cost = function(x){
cost = rexp(x,1/60)
prob = sample(c(0,1/60),x,prob=c(7/8,1/8),replace=TRUE)
sum(cost[prob>0])
}

然后生成每年的故障次数:

Then generate the number of breakdowns per year:

set.seed(111)
N <- rpois(500000, 2)

历年迭代,如果为0,则返回0:

Iterate over the years, if 0, we return 0:

set.seed(111)
sim = sapply(N,function(i)if(i==0){0}else{sum(sim_cost(i))})

mean(sim)
[1] 14.98248
var(sim)
[1] 1797.549

您需要进行大量模拟,但上面应该是您可以开始优化以使其更接近的代码.

You need quite a number of simulations, but above should be a code that you can start to optimize to get it closer.

这篇关于使用蒙特卡罗模拟计算方差的期望值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆