假设有个飞人,一开始在xyz坐标轴平面的原点(0,0,0)处。 每过一秒,它会随机地往一个方向北(y正半轴)南(y负半轴)东(x正半轴)西(x负半轴)上(z正半轴)下(z负半轴)飞n个单位长度(n取值范围是1-10, 包括10)能飞到z<0处
要求 : 记录过了1秒, 2秒, 100000秒后, 它距离原点的矩离s
**
我的代码:
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((x2+y2)0.5)
elif mydir == 2:
y+=1
distance.append((x2+y2)0.5)
elif mydir == 3:
x-=1
distance.append((x2+y2)0.5)
else:
y-=1
distance.append((x2+y2)**0.5)
plt.plot(range(100000),distance)
plt.show()
plt.close()
import random
import matplotlib.pyplot as plt
# 初始坐标位置
pos = [0,0,0]
# 用以记录每步的移动及移动后坐标位置
steps=[]
# 移动次数
step = 100000
# 初始化定义方向,及方向影响的坐标轴
arrow = {'e':[1,0,0],'w':[-1,0,0],'s':[0,-1,0],'n':[0,1,0],'u':[0,0,1],'d':[0,0,-1]}
distance=[]
for i in range(step):
# 随机获取移动方向
r = random.choice(list(set(arrow)))
# 获取移动距离
l = random.randint(1, 10)
# 将移动方向和距离更新至坐标点中
pos[0] += arrow[r][0]*l
pos[1] += arrow[r][1]*l
pos[2] += arrow[r][2]*l
# 记录移动信息及坐标点
steps.append(r+str(l)+' ['+','.join([str(n) for n in pos])+']')
# 记录当前坐标点距离原点距离
distance.append((pos[0]**2+pos[1]**2+pos[2]**2)**0.5)
#print('\n'.join(steps))
plt.plot(range(step),distance)
plt.show()
plt.close()
import random
import matplotlib.pyplot as plt
x = 0
y = 0
z = 0
i = 0
distance = []
for i in range(100000):
mydir = random.randint(1, 6)
if mydir == 1:
x += 1
distance.append((x ^ 2 + y ^ 2 + z ^ 2) * 0.5)
elif mydir == 2:
y += 1
distance.append((x ^ 2 + y ^ 2 + z ^ 2) * 0.5)
elif mydir == 3:
z += 1
distance.append((x ^ 2 + y ^ 2 + z ^ 2) * 0.5)
elif mydir == 4:
x -= 1
distance.append((x ^ 2 + y ^ 2 + z ^ 2) * 0.5)
elif mydir == 5:
y -= 1
distance.append((x ^ 2 + y ^ 2 + z ^ 2) * 0.5)
else:
z -= 1
distance.append((x ^ 2 + y ^ 2 + z ^ 2) * 0.5)
i += 1
plt.plot(range(100000), distance)
plt.show()
plt.close()