python - 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
解决方案
使用 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)
推荐阅读
- python - Python脚本问题:“sh:1:语法错误:反引号替换中的EOF”
- marklogic - 带有 xsi:noNamespaceSchemaLocation 的片段根上的 XDMP-PARENTLINK 错误
- android - 如何在我的布局顶部创建外部阴影?
- python - 会话已设置但未保留
- javascript - redux-saga API 调用返回什么?(举个例子)
- tensorflow - 使用所有可用于 tf.estimator.Estimator().predict() 的 GPU 设备
- c - 为什么我不能将多字节字符串转换为宽字符串?即使 mbstring 似乎有效,mbsrtowcs 也会因 EILSEQ 失败
- spring-boot - 如何在 Spring Boot 2.1.0 启动器配置中将 spring.main.allow-bean-definition-overriding 设置为 true
- python - Pyspark 错误:使用交叉验证时“字段 rawPrediction 不存在”
- libgdx - LibGDX 粒子效果颜色分辨率不同