我正在用R编写一个程序,以对此处解释的https://www.youtube.com/watch?v=4Lb-6rxZxx0的Monty Hall问题进行一些模拟。
考虑一下此代码,public class DataGridListBoxColumn : DataGridTextColumn
{
TextBlock tx = new TextBlock();
public DataGridListBoxColumn()
{
tx.Name = "TxB";
}
protected override FrameworkElement GenerateEditingElement(DataGridCell cell, Object dataItem)
{
Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridListBoxColumn), 1);
b.Path = new PropertyPath("ListItem");
tx.SetBinding(TextBlock.TextProperty, b);
return cell;
}
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var x = ListItem;
Debugger.Break(); //here x is null
}
public List<Student> ListItem
{
get { return (List<Student>)GetValue(ItemSourceProperty); }
set { SetValue(ItemSourceProperty, value); }
}
public static readonly DependencyProperty ItemSourceProperty = DependencyProperty.Register("ListItem", typeof(List<Student>), typeof(DataGridListBoxColumn));
}
每次“应该”为3,但不是。
sample(setdiff(doors, c(pick, car)),1)
知道我要去哪里哪里吗?
谢谢。
答案 0 :(得分:2)
您的问题是,自从您结束呼叫sample.int
doors <- 3L
pick <- sample(doors, 1)
car <- sample(doors, 1)
class(setdiff(doors, c(pick, car)))
#R [1] "integer"
和
length(setdiff(doors, c(pick, car)))
#R [1] 1
请参见help("sample.int")
或
body(sample)
#R {
#R if (length(x) == 1L && is.numeric(x) && is.finite(x) && x >=
#R 1) {
#R if (missing(size))
#R size <- x
#R sample.int(x, size, replace, prob)
#R }
#R else {
#R ...
除非您的变量集中有多个变量,否则采样毫无意义。
答案 1 :(得分:0)
这是我为解决该问题而编写的最终代码。我使用了if语句仅在必要时才调用样本,在这种情况下,应聘者会开车上门。我感觉到,额外条件语句的窃听比强迫样本以非预期的方式工作的代价更有价值。
doors <- 1:3
trials <- 1000
games <- do.call(rbind, lapply(1:trials, function(i){
pick <- sample(doors, 1)
car <- sample(doors, 1)
#open the door the contestant didn't pick and isn't the car
open_door <- setdiff(doors, c(pick, car))
#if pick and car are the same, there are two possible doors to open
#so pick one at random
#note, sample will malfunction if there is only 1 int passed to it. See documentation.
#this is the reason for if statement, only deal with the case where there is more than
#one int passed
if(length(open_door)>1) open_door <- sample(open_door, 1)
#switch to the door that isn't picked and is closed
switch_to <- setdiff(doors, c(pick, open_door))
data.frame(pick, car, open_door, switch_to)
}))
games$switch_wins <- ifelse(games$switch_to == games$car, 1, 0)
games$stay_wins <- ifelse(games$pick == games$car, 1, 0)
cat("Switch wins: ", sum(games$switch_wins)/nrow(games), "Stay wins: ",
sum(games$stay_wins)/nrow(games), "\n")
输出:
Switch wins: 0.672 Stay wins: 0.328