首页 > 解决方案 > python中的随机游走绘图

问题描述

我一直在阅读 Jesse M. Kinder 和 Philip Nelson 所著的“物理建模 Python 学生指南”一书,并且有一个练习,我被指示构建一个布朗运动模拟器/随机游走模拟器并绘制它。我不知道为什么我的代码不起作用,我希望我能从你那里得到一些帮助:

import numpy as np
import matplotlib.pyplot as plt
from numpy.random import random as rng

def Brownian_motion(steps):
    """
    this is a random walk function
    define the number of steps to be taken as a integer value
    """
    #these are the random numbers
    steps_x = rng(steps)
    steps_y = rng(steps)

    #Here I change the random numbers to 1 or -1
    pace_x = (steps_x < 0.5)
    for i in pace_x:
        if i == False:
            pace_x[i] = -1
        else:
            pace_x[i] = 1
        return pace_x

    pace_y = (steps_y < 0.5)
    for i in pace_y:
        if i == False:
            pace_y[i] = -1
        else:
            pace_x[i] = 1
        return pace_y

    plt.plot(np.cumsum(pace_x), np.cumsum(pace_y))
    plt.show()

Brownian_motion(500)

它不会抛出错误,但我无法让它绘制

编辑:

这与我期望看到的类似:

http://people.sc.fsu.edu/~jburkardt/m_src/random_walk_2d_simulation/walks_1_steps_1000_plot.png

标签: python

解决方案


使用 numpy,您可以创建更高效​​的布尔切片。请注意,这不适用于 Python 列表/元组。

import numpy as np
import matplotlib.pyplot as plt
from numpy.random import random as rng

def Brownian_motion(steps):
    """
    this is a random walk function
    define the number of steps to be taken as a integer value
    """
    #these are the random numbers
    steps_x = rng(steps)
    steps_y = rng(steps)

    pace_x = np.ones_like(steps_x)
    idx = steps_x < 0.5
    pace_x[idx] = -1

    idy = steps_y < 0.5
    pace_y = np.ones_like(steps_y)
    pace_y[idy] = -1

    plt.plot(np.cumsum(pace_x), np.cumsum(pace_y))
    # plt.axis("equal") 
    # I would also add this. This way your plot won't be
    # distorted.
    plt.show()

a = Brownian_motion(500)

随机游走


推荐阅读