如果 X =显示掷三枚硬币时的头数,请找到 P(X = 1) >和 E(X) 。
实验具有以下分布:
根据我的计算,
P(X = 1) = 0.375≈0.40
E(X) = 1.50
其中 n =实验的重复次数。
源代码
noOfExperiments = 10000;
mySample <- sample(c(0,1,2,3), noOfExperiments, replace = T)
outcomeCount <- length(which(mySample==1))
prob <- outcomeCount / noOfExperiments
eX <- sum(mySample)/noOfExperiments
根据上面的代码,我获得了
P(X = 1) = 0.2518
E(X) = 1.4917≈1.50
似乎 E(X) 的值很好,但是 P(X = 1) 不能正确显示。
我的代码有什么问题?
修改:
我已经根据 Edward Carney 的评论编写了以下代码。
noOfExperiments = 1000;
mySample <- replicate(noOfExperiments, sum(sample(c(0, 1), 3, replace=T)) )
outcomeCount <- length(which(mySample==1))
prob <- outcomeCount/noOfExperiments
eX <- sum(mySample)/noOfExperiments
注意: related question。