使用 random 模块生成一维随机游走

发布于 2025-01-18 00:48:05 字数 656 浏览 4 评论 0原文

我试图仅使用 random 模块生成一维随机游走。如果某个时刻的位置是x,那么下一个位置可以等概率是x+1x-1。我需要在 100 次移动后找到最终位置 (start=0)。

我开发了以下代码,但我不确定应该如何定义选择之间的相等概率。

import random
def randomwalk1D(n):
    x = 0
    start = x
    xposition = [start]
    probabilities = [0.5, 0.5]
    for i in range(1, n + 1):
        step = random.choice(probabilities)
        if step > probabilities[0]:
            x += 1
        elif step < probabilities[1]:
            x -= 1
        xposition.append(start)
    return xposition

该函数仅返回零作为结果(输入n = 100)。我只想使用 random 模块。有人可以建议从这里做什么吗?

I was trying to generate a random walk in 1D just with the random module. If a position at a certain moment is x, then the next position can be x+1 or x-1 with equal probability. I need to find the final position after 100 moves (start=0).

I have developed the following code, but I am not sure how I should should define the equal probability among the choices.

import random
def randomwalk1D(n):
    x = 0
    start = x
    xposition = [start]
    probabilities = [0.5, 0.5]
    for i in range(1, n + 1):
        step = random.choice(probabilities)
        if step > probabilities[0]:
            x += 1
        elif step < probabilities[1]:
            x -= 1
        xposition.append(start)
    return xposition

The function return just zeroes as result (putting n = 100). I only want to only use the random module. Could someone advise on what to do from here?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

绿萝 2025-01-25 00:48:05

您的代码有两个问题:

  1. 您需要将 -11 的选择传递给 random.choice(),而不是权重这些选择。您还可以摆脱与概率和采样步骤中的元素的直接比较。如果您想要加权采样,请使用numpy.random.choice
  2. 您重复将 start 添加到 xpositions 列表中,即使您从未更新它。要解决此问题,请改为附加 x,它表示实际的当前位置。

这是解决这两个问题的代码片段。

import random
def randomwalk1D(n):
    x = 0
    start = x
    xposition = [start]
    probabilities = [-1, 1]
    for i in range(1, n + 1):
        x += random.choice(probabilities)
        xposition.append(x)
    return xposition

print(randomwalk1D(100))

There are two issues with your code:

  1. You need to pass the choices of -1 and 1 to random.choice(), not the weights of those choices. You can also get rid of the direct comparisons with the elements from probabilities and the sampled step. If you want weighted sampling, use numpy.random.choice.
  2. You're adding start to the xpositions list repeatedly, even though you never update it. To resolve, append x instead, which represents the actual current position.

Here is a code snippet that resolves both issues.

import random
def randomwalk1D(n):
    x = 0
    start = x
    xposition = [start]
    probabilities = [-1, 1]
    for i in range(1, n + 1):
        x += random.choice(probabilities)
        xposition.append(x)
    return xposition

print(randomwalk1D(100))
冷夜 2025-01-25 00:48:05

已经发布了一些很好的答案,所以我会补充说可以进行一些优化:

import random
def randomwalk1D(n):
    x = 0
    xposition = [x]
    for _ in range(n):
        step = random.randint(0,1)
        if step:
            x += 1
        else:
            x -= 1
        xposition.append(x)
    return xposition

这会删除 start,因为我们可以简单地定义 x = 0 并且因为您如果希望您的列表以此值开头,请实例化包含 [x] 的列表。

    x = 0
    xposition = [x]

我们使用的是 for _ in range(n),而不是 for i in range(1, n + 1):。这会循环相同的次数,但从默认值 0 开始。因为没有使用变量i,所以我们使用_,这是一个标准,表示该值并不重要,我们只想循环某个数字次。

    for _ in range(n):

我们使用 random.randint(0,1),而不是数字列表和 random.randchoice。这个范围是包含在内的,所以它将返回 0 或 1。

step = random.randint(0,1)

然后,因为 1 是“true”,我们可以简单地测试 if step: 来测试是否为 1,并且否则使用 else:

        if step:
            x += 1
        else:
            x -= 1
>>> randomwalk1D(10) 
[0, 1, 2, 3, 2, 3, 4, 3, 4, 3, 4]

编辑:

如果需要加权数字,可以对代码进行以下修改:

        choices = (0,1)
        weights = (10,1)
        step = random.choices(choices, weights=weights).pop()

step 将被定义为 0 或 1,其中 0 的可能性是 1 的 10 倍。

There's some good answers already posted, so I'll add that there's some optimizations that could be made:

import random
def randomwalk1D(n):
    x = 0
    xposition = [x]
    for _ in range(n):
        step = random.randint(0,1)
        if step:
            x += 1
        else:
            x -= 1
        xposition.append(x)
    return xposition

This removes start, as we can simply define x = 0 and since you want your list to start with this value, instantiate the list with [x] included.

    x = 0
    xposition = [x]

Instead of for i in range(1, n + 1):, we're using for _ in range(n). This cycles the same amount of times, but starting at the default of 0 instead. Because there's no use of the variable i, we're using _ which is a standard to indicate that the value doesn't matter, we only want to cycle a certain number of times.

    for _ in range(n):

Instead of a list of numbers and random.randchoice, we're using random.randint(0,1). This range is inclusive, so it will return 0, or 1.

step = random.randint(0,1)

Then, because 1 is "truthy", we can simply test if step: to test if 1, and then use else: otherwise.

        if step:
            x += 1
        else:
            x -= 1
>>> randomwalk1D(10) 
[0, 1, 2, 3, 2, 3, 4, 3, 4, 3, 4]

Edit:

If weighted numbers are needed, the following modification could be made to the code:

        choices = (0,1)
        weights = (10,1)
        step = random.choices(choices, weights=weights).pop()

step will be defined as either 0 or 1, with 0 being 10 times more likely than 1.

萌吟 2025-01-25 00:48:05

我认为您的代码中有两个单独的问题,导致您看到的结果:

  • random.choice(probabilities) 表达式的结果始终为 0.5。这样,下面的两个 if 语句就永远不会被触发,并且 x 始终保持相同的值。
  • 当您使用 xposition.append 附加步骤时,您将附加起始值,该起始值在 for 循环的迭代中也保持不变,因此只会附加 0。

此外,对于 random.choice 的实际用途可能会有些混乱。
它需要一个可迭代对象,并统一选择其中一项进行输出。由于您给了它 [0.5, 0.5] 这意味着您只能得到 0.5 作为输出。也许您可以使用random.uniform(0, 1)作为step来生成一个统一的随机数。这样你就可以根据 step >= 0.5step <= 0.5 来决定行走的方向。 0.5。

I think there are two separate problems in your code, that are leading to the results you are seeing:

  • The result of your random.choice(probabilities) expression is always a value of 0.5. With that, both of the following if statements can never be triggered, and x always remains the same value.
  • When you append the steps with xposition.append you are appending the start value, which also remains the same over iterations of the for loop, so only 0 will ever be appended.

Additionally, there might be some confusion about what random.choice actually does.
It takes a iterable, and uniformly chooses one of it's items to output. Since you have given it [0.5, 0.5] that means, you can only ever get 0.5 as an output. Perhaps you could just generate a uniformly random number, using random.uniform(0, 1) as step. That way you can just decide the direction to walk in based on step >= 0.5 or step < 0.5.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文