from random import choice
x_direction = choice([1,-1])#从-1和1中随即选择一个数赋值给变量
random_walk.py
from random import choice
class RandomWalk:
'''生成一个随机漫步的数据类'''
def __init__(self,num_points = 5000):
'''初始化随机漫步的属性'''
self.num_points = num_points #采用默认参数赋值给全局变量,这样可以方便后续的修改
#所有随即漫步都始于(0,0)
self.x_values =[0]
self.y_values =[0]
def fill_walk(self):
#计算随即漫步包含的所有点
#不断漫步,知道达到指定长度
while len(self.x_values) < self.num_points:
#决定前进的方向以及沿着个方向前进的距离
x_direction = choice([1,-1])
x_distance = choice([0,1,2,3,4])
x_step = x_direction*x_distance
y_direction = choice([1,-1])
y_distance = choice([0,1,2,3,4])
y_step = y_direction*y_distance
#拒绝原地踏步
if x_step == 0 and y_step == 0:
continue
#计算下一个点的x值和y值
x = self.x_values[-1] + x_step#x[-1]是最近一次x的坐标
y = self.y_values[-1] + y_step
#将x and y添加到储存x and y的数组中
self.x_values.append(x)
self.y_values.append(y)
rw_visual.py
import matplotlib.pyplot as plt
from random_walk import RandomWalk
#创建一个RandomWalk实例
rw =RandomWalk(5_000)
rw.fill_walk()
#将所有的点度绘制出来
plt.style.use('classic')
fig,ax = plt.subplots(1,1,figsize=(15,9),dpi=128)#如果知道屏幕分辨率可以通过dpi参数像其传递以充分利用屏幕,也就是满屏效果。
ax.set_title("RandomWalk")
point_numbers = range(rw.num_points)
ax.scatter(rw.x_values,rw.y_values,s=15,c=point_numbers,cmap=plt.cm.Blues,edgecolor='none')#edgecolor='none'是消除标签点的外轮廓线
#绘制起点和终点
ax.scatter(0,0,s=100,c='green',edgecolor='none')#绘制起点
ax.scatter(rw.x_values[-1],rw.y_values[-1],s=100,c='red',edgecolor='none')#绘制终点
#隐藏坐标轴
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.show()
random 模块choice函数:
random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.
seq:序列,不一定是数字也可以是字符串列表,元组等
random.choices(population, weights=None, *, cum_weights=None, k=1)
Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.
If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if acum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.
If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence. It is a TypeError to specify both weights and cum_weights.
The weights or cum_weights can use any numeric type that interoperates with the float values returned by random() (that includes integers, floats, and fractions but excludes decimals). Weights are assumed to be non-negative and finite. A ValueError is raised if all weights are zero.
For a given seed, the choices() function with equal weighting typically produces a different sequence than repeated calls to choice(). The algorithm used by choices() uses floating point arithmetic for internal consistency and speed. The algorithm used by choice() defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.
New in version 3.6.
Changed in version 3.9: Raises a ValueError if all weights are zero.