首页 > 解决方案 > 调整绘图

问题描述

我想绘制 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()

标签: pythonmatplotlib

解决方案


以下代码提供了所需的输出:

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")

推荐阅读