模拟随机游走 [英] Simulating a Random Walk

查看:128
本文介绍了模拟随机游走的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Xn可以取-1或1的值,概率为0.5. Sn = Sn-1 + Xn我该如何计算 Sn = X1 + X2 +:::+ Xn在时间n处观察到的部分和.我正在尝试在这里模拟随机行走. 我做了以下事情,但我不确定它是正确的:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆