在R中掷出3个公平的硬币(2)

时间:2019-03-08 01:52:42

标签: r statistics probability

  

如果 X =显示掷三枚硬币时的头数,请找到 P(X = 1) >和 E(X)

实验具有以下分布:

enter image description here

根据我的计算,
P(X = 1) = 0.375≈0.40
E(X) = 1.50

然后,enter image description here

其中 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) 不能正确显示。

我的代码有什么问题?

修改:

enter image description here

我已经根据 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

enter image description here


注意: related question

0 个答案:

没有答案