python - 调整绘图
问题描述
我想绘制 T 的根以及随机游走作为比较 - 但我不知道为什么这不起作用......作为错误消息,我得到“元组索引超出范围” - 也许我只是忽略了一件愚蠢的小事......无论如何提前谢谢
P_dis = []
N = 50
# N = the number of iterations i.e. the number of iterations of the loop
# below
T = 1000
allx = np.array([]).reshape(0,T)
ally = np.array([]).reshape(0,T)
allD = np.array([]).reshape(0,T)
allsqrt = np.array([]).reshape(0,T)
for j in range(N):
# T = time steps i.e. the number of jumps the particle makes
x_pos = [0]
y_pos = [0]
# initally empty lists that will be appended below
for i in range(1,T):
A = random.uniform(0 , 1)
B = A * 2 * math.pi
current_x = x_pos[i-1]
current_y = y_pos[i-1]
next_x = current_x + math.cos(B)
# takes previous xpos and applies
next_y = current_y + math.sin(B)
x_pos = x_pos + [next_x]
# appends the next x list with xpos and stores
y_pos = y_pos + [next_y]
sqrt = np.sqrt(i)
dis = np.sqrt((0 - x_pos[T - 1])**2 + (0 - y_pos[T - 1])**2)
dis = np.sqrt((0 - np.array(x_pos))**2 + (0 - np.array(y_pos))**2)
allD = np.vstack([allD,dis])
allx = np.vstack([allx,np.array(x_pos)])
ally = np.vstack([ally,np.array(y_pos)])
allsqrt = np.vstack([allsqrt,dis])
P_dis.append(dis)
print(j)
plt.plot(np.arange(0,T),np.mean(allD,0),'g')
plt.plot(np.arange(0,T),np.mean(sqrt,0),'r')
plt.xlabel("N")
plt.ylabel("A")
plt.figure()
解决方案
以下代码提供了所需的输出:
import numpy as np
import math
import matplotlib.pyplot as plt
random = np.random
P_dis = []
N = 50
# N = the number of iterations i.e. the number of iterations of the loop
# below
T = 1000
allx = np.array([]).reshape(0,T)
ally = np.array([]).reshape(0,T)
allD = np.array([]).reshape(0,T)
allsqrt = np.array([]).reshape(0,T)
for j in range(N):
# T = time steps i.e. the number of jumps the particle makes
x_pos = [0]
y_pos = [0]
# initally empty lists that will be appended below
for i in range(1,T):
A = random.uniform(0 , 1)
B = A * 2 * math.pi
current_x = x_pos[i-1]
current_y = y_pos[i-1]
next_x = current_x + math.cos(B)
# takes previous xpos and applies
next_y = current_y + math.sin(B)
x_pos = x_pos + [next_x]
# appends the next x list with xpos and stores
y_pos = y_pos + [next_y]
sqrt = np.sqrt(i)
dis = np.sqrt((0 - x_pos[T - 1])**2 + (0 - y_pos[T - 1])**2)
dis = np.sqrt((0 - np.array(x_pos))**2 + (0 - np.array(y_pos))**2)
allD = np.vstack([allD,dis])
allx = np.vstack([allx,np.array(x_pos)])
ally = np.vstack([ally,np.array(y_pos)])
allsqrt = np.vstack([allsqrt,dis])
P_dis.append(dis)
print(j)
plt.plot(np.arange(0,T),np.mean(allD,0),'g')
plt.plot(np.arange(0,T),np.sqrt(np.arange(0, T)),'r')
plt.xlabel("N")
plt.ylabel("A")
推荐阅读
- spring - Flutter,通过 Dio/http 将嵌套的 FormData 发送到服务器
- java - Java输入读取字符串进行验证
- cookies - 如何确保 CloudFront 从我的 Elastic Beanstalk REST API 应用程序返回 cookie
- snowflake-cloud-data-platform - 如何检查一个json是否包含雪花中的另一个json
- javascript - Angular 7在创建时间超过6个月时隐藏一个div
- python - 用用户输入列表替换列表
- android - Android 11 - 访问 Android/data 目录
- php - PHP AJAX登录表单运行AJAX失败代码
- html - 蓝色选择区域太大
- python - Django Session 没有得到适当的更新