monte carlo 模拟错误,不会更新计数
monte carlo simulation error, wont update count
nrep = 1000
count = 0
x = rnorm(n = 30, mean = 20, sd = 3)
y = rnorm(n = 30, mean = 22, sd = 5)
for (i in 1:nrep) {
a = sample(x, 1)
b = sample(y, 1)
if ((a | b) > 25) count = count + 1
}
print(count/nrep)
当我 运行 这个 monte carlo 模拟它时 returns 0。如果我从循环中删除 a 和 b 并只使用 x 和 y 它会花费太长时间并且 returns 只是错误 "The condition has length > 1 and only the first element will be used"。
我想让它计算 1000 次中 a 或 b 中较大的那个大于 25 的次数。
您的 'if' 语句中的逻辑运算指定不正确。使用 OR 运算符 '|' 时您必须在“|”的任一侧具有您希望组合的逻辑值。下面的代码显示了 'if' 语句的注释版本下的正确规范。
此外,“|” will return TRUE 任何时候任一操作数不为零。这是因为 R 的 '|'运算符将任何非零数值解释为 TRUE(零本身被解释为 FALSE。
nrep = 1000
count = 0
x = rnorm(n = 30, mean = 20, sd = 3)
y = rnorm(n = 30, mean = 22, sd = 5)
for (i in 1:nrep) {
a = sample(x, 1)
b = sample(y, 1)
# if ((a | b) > 25) count = count + 1
if (a > 25 | b > 25) count = count + 1
}
print(count/nrep)
nrep = 1000
count = 0
x = rnorm(n = 30, mean = 20, sd = 3)
y = rnorm(n = 30, mean = 22, sd = 5)
for (i in 1:nrep) {
a = sample(x, 1)
b = sample(y, 1)
if ((a | b) > 25) count = count + 1
}
print(count/nrep)
当我 运行 这个 monte carlo 模拟它时 returns 0。如果我从循环中删除 a 和 b 并只使用 x 和 y 它会花费太长时间并且 returns 只是错误 "The condition has length > 1 and only the first element will be used"。
我想让它计算 1000 次中 a 或 b 中较大的那个大于 25 的次数。
您的 'if' 语句中的逻辑运算指定不正确。使用 OR 运算符 '|' 时您必须在“|”的任一侧具有您希望组合的逻辑值。下面的代码显示了 'if' 语句的注释版本下的正确规范。
此外,“|” will return TRUE 任何时候任一操作数不为零。这是因为 R 的 '|'运算符将任何非零数值解释为 TRUE(零本身被解释为 FALSE。
nrep = 1000
count = 0
x = rnorm(n = 30, mean = 20, sd = 3)
y = rnorm(n = 30, mean = 22, sd = 5)
for (i in 1:nrep) {
a = sample(x, 1)
b = sample(y, 1)
# if ((a | b) > 25) count = count + 1
if (a > 25 | b > 25) count = count + 1
}
print(count/nrep)