模拟随机游走 [英] Simulating a Random Walk
问题描述
rw <- function(n){
x=numeric(n)
xdir=c(TRUE, FALSE)
step=c(1,-1)
for (i in 2:n)
if (sample(xdir,1)) {
x[i]=x[i-1]+sample(step,1)
} else {
x[i]=x[i-1]
}
list(x=x)
}
请帮助!
此答案只是为了解释为什么您的代码无法正常工作. @ jake-burkhead给出了您实际编写代码的方式.
在此代码中,您只走了一半的时间.这是因为您要从xdir
采样以确定是否移动.相反,我建议您在循环内进行以下操作:
for(i in 2:n){
x[i] <- x[i - 1] + sample(step, 1)
}
sample(step, 1)
调用决定步行是否移动1
或-1
.
要计算部分和,可以在生成x
之后使用cumsum()
.结果将是步行中给定点的部分和的向量.
Xn can take values of -1 or 1 each with a probability of 0.5. And Sn= Sn-1 + Xn How can I compute the partial sum observed at time n given by Sn = X1 + X2 + : : : + Xn. I'm trying to simulate a random walk here. I did the following but I'm not exactly sure it's right:
rw <- function(n){
x=numeric(n)
xdir=c(TRUE, FALSE)
step=c(1,-1)
for (i in 2:n)
if (sample(xdir,1)) {
x[i]=x[i-1]+sample(step,1)
} else {
x[i]=x[i-1]
}
list(x=x)
}
Please Help!
This answer is just to explain why your code did not work. @jake-burkhead gave the way you should actually write the code.
In this code, you only make a step half of the time. This is because you are sampling from xdir
to decide if you move or not. Instead, I would recommend you the following inside your loop:
for(i in 2:n){
x[i] <- x[i - 1] + sample(step, 1)
}
The sample(step, 1)
call decides if the walk moves 1
or -1
.
To compute the partial sums, you can use cumsum()
after you generate x
. The result will be a vector of the partial sums at a given point in the walk.
这篇关于模拟随机游走的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!