在R中运行蒙特卡罗模拟,并从中构建向量
我试图编写的函数的目标是执行以下操作在R中运行蒙特卡罗模拟,并从中构建向量,r,montecarlo,R,Montecarlo,我试图编写的函数的目标是执行以下操作 随机选择一个介于0和10之间的数字N 评估eq(N)=P 在0和1之间随机生成一个数字L 如果L>P,我们丢弃这个数字,否则,我们将P添加到一个数字向量中 重复此操作数次,等于函数的输入运行 尝试运行NeutonRejector会导致以下错误: Error: unexpected '=' in: " U <- U+1 if(U =" > } Error: unexpected '}' in " }&quo
N
eq(N)=P
L
L>P
,我们丢弃这个数字,否则,我们将P
添加到一个数字向量中运行
NeutonRejector
会导致以下错误:
Error: unexpected '=' in:
" U <- U+1
if(U ="
> }
Error: unexpected '}' in " }"
> }
Error: unexpected '}' in "}"
错误:中出现意外的“=”:
“U一些修正:
- 通过
==
- 使用
runif(1,min=0,max=1)
获取一个随机数
if
语句而不是ifelse
使用==
测试等式谢谢!前两个只是愚蠢的打字错误,但我不知道使用if而不是ifelse。这仍然是一个学习过程!
eq = function(x){x*(exp(-x/1.4))}
values <- c()
U <- 0
neutronrejector = function(runs){
repeat{
N = runif(1, min=0, max=10)
P = eq(N)
L = runif(100, min=0, max=1)
ifelse(L > P, , values = c(N, values))
U = U+1
if(U = runs) break
}
}
neutronrejector = function(runs){
repeat{
N = runif(1, min=0, max=10)
P = eq(N)
L = runif(1, min=0, max=1)
if (L > P) values = c(N, values)
U = U+1
if(U == runs) break
}
values
}
neutronrejector(10)
[1] 4.997457 7.699111 7.009196 5.515345 3.422422 9.495239 8.758963 2.209809 6.392655