假设在二维平面内一个点(初始位置设为(0,0))一次能随机的沿着东西南北的其中一个方向走一个单位,求100000次后以该点与原点的距离为y轴走的次数为x轴的图像,以下是我个人的代码:
import random
import matplotlib.pyplot as plt
import numpy as np
xl = [0]
y = [0]
for i in range(100000):
mydir = random.randint(1,4)
mystep = 1
if mydir == 1:
xl.append(xl[-1]+mystep)
if mydir == 2:
xl.append(xl[-1]-mystep)
if mydir == 3:
y.append(y[-1]+mystep)
xl.append(xl[-1]+(xl[-1]**2+y[-1]**2)**0.5)
if mydir == 4:
y.append(y[-1]-mystep)
xl.append(xl[-1]+(xl[-1]**2+y[-1]**2)**0.5)
xl=np.array(xl)
plt.plot(np.abs(xl))
plt.show()
plt.close()
修改后如下有帮助望采纳~
import random
import matplotlib.pyplot as plt
x=0
y=0
distance=[]
for i in range(100000):
mydir = random.randint(1,4)
if mydir == 1:
x+=1
distance.append((x**2+y**2)**0.5)
elif mydir == 2:
y+=1
distance.append((x**2+y**2)**0.5)
elif mydir == 3:
x-=1
distance.append((x**2+y**2)**0.5)
else:
y-=1
distance.append((x**2+y**2)**0.5)
plt.plot(range(100000),distance)
plt.show()
# plt.close()
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()