假设有个人,一开始在xy坐标轴平面的原点(0,0)处。每过一秒,它会随机地往一个方向北(y正半轴)南(y负半轴)东(x 正半轴)西(x负半轴)走1步 1. 记录过了1秒, 2秒, 100000秒后,它距离原点的矩离s 2. 把距离和时间的关系画出来(二维平面图,x轴为时间,y轴为距离) 3. 把它的路线画出来
import matplotlib.pyplot as plt
import random
fig = plt.figure(figsize=(16,8))
fig.add_subplot(121)
s = 0
sList = [0] # 距离的列表
# 坐标x,y.
direction = ["北","南","东","西"]
x,y = (0,0)
xList = [0] # x坐标
yList = [0] # y坐标
for i in range(100000-1):
stepDirection = random.choice(direction)
if stepDirection == "北":
y += 1
elif stepDirection == "南":
y -= 1
elif stepDirection == "东":
x += 1
else:
x -= 1
s = (x**2 + y**2) ** 0.5
sList.append(s)
xList.append(x)
yList.append(y)
plt.plot(list(range(0,100000)),sList)
plt.xlabel("Time")
plt.ylabel("Distance")
fig.add_subplot(122)
plt.plot(xList,yList)
plt.xlabel("X")
plt.ylabel("Y")
plt.show()
结果:
如果觉得答案对你有帮助,请点击下采纳,谢谢~
好奇怪,同样的问题问了两次,我已经回答过了。
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> def test():
x, y = [0], [0]
for i in range(1000):
r = np.random.random()
if r >= 0.75: # 东
x.append(x[-1]+1)
y.append(y[-1])
elif r >= 0.5: # 西
x.append(x[-1]-1)
y.append(y[-1])
elif r >= 0.25: # 南
y.append(y[-1]-1)
x.append(x[-1])
else: # 北
y.append(y[-1]+1)
x.append(x[-1])
x, y = np.array(x), np.array(y)
d = np.hypot(x, y) # 距离
print('第1、2、1000秒后距离原点的距离分别为:%f、%f、%f步'%(d[1], d[2], d[1000]))
plt.plot(d)
plt.show()
>>> test()
第1、2、1000秒后距离远点的距离分别为:1.000000、2.000000、28.635642步
https://img-mid.csdnimg.cn/release/static/image/mid/ask/564047407636190.png