为何2D随机步长实验中总路程与步数平方根呈二次关系而非线性?
2D随机步长问题:实验与理论不符的原因分析
我正在研究2D随机步长问题,需证明总路程与步数的平方根呈线性关系,但实验结果显示总路程与步数线性相关、与步数平方根呈二次关系。附上实验代码,请问是代码存在错误,还是我对理论存在误解?
我尝试将代码与数学表达式对应,未发现差异,不知问题出在哪里。
原实验代码
import matplotlib.pyplot as plt import random import math #defining the initial values of the variables to start at 0 and the number of iterations (n) to be 1000. x = 0 y = 0 n = 1000 listx = [] listy = [] listr= [] listn = [] r = 0 #starting a for loop with n iterations. for i in range (0, n+1): #Appending all x values to listx listx.append(x) #Appending all y values to listy listy.append(y) #Generating random coordinates in both dimensions in the range between -1 and 1 for both x and y values. x -= (random.random()-0.5)*2 y -= (random.random()-0.5)*2 #Defining r to be the distance covered each step using the Pythagorean theorem and appending the total distance covered after each step to listr r += math.sqrt(x**2 + y**2) listr.append(r) for i in range(0, n+1): listn.append(math.sqrt(i)) #Plotting the random steps taken using each given value of x and y. plt.plot(listx, listy) plt.xlabel("steps in the x-axis") plt.ylabel("steps in the y-axis") plt.title("Visualization of the random steps taken") plt.show() #Plotting the relation between the total distance covered and the number of iteration. plt.plot(listn, listr) plt.xlabel("square root of n") plt.ylabel("distance") plt.title("Distance covered vs the number of iteration") plt.show()
核心问题:代码逻辑错误 + 概念混淆
1. 总路程计算完全错误
你代码中r += math.sqrt(x**2 + y**2)的逻辑是累加当前位置到原点的距离,而不是累加每一步的移动距离(步长)。这直接导致r的增长速度远快于实际总路程,最终呈现和√n的二次关系。
正确的总路程计算应该是:每一步计算当前位移的变化量Δx和Δy,然后累加sqrt(Δx² + Δy²)得到总路程。
2. 混淆了「总路程」和「位移」的理论定义
随机步的核心理论结论是:位移的均方值与步数n线性相关(即<r²> ∝ n,因此平均位移<r> ∝ √n),但总路程是每一步步长的总和——如果每一步步长固定,总路程必然和n线性相关,和√n呈二次关系。你把「位移」的理论结论错误套用到了「总路程」上,这是概念误解。
修正后的代码
下面是修正了总路程计算、采用标准随机步(固定步长、随机角度)的代码:
import matplotlib.pyplot as plt import random import math x, y = 0, 0 n = 1000 listx = [x] listy = [y] total_distance_list = [] sqrt_n_list = [] total_distance = 0 for i in range(1, n+1): # 生成随机角度,步长固定为1的标准2D随机步 angle = random.uniform(0, 2 * math.pi) dx = math.cos(angle) dy = math.sin(angle) # 更新位置并记录 x += dx y += dy listx.append(x) listy.append(y) # 累加每一步的步长到总路程 total_distance += math.sqrt(dx**2 + dy**2) total_distance_list.append(total_distance) # 记录步数的平方根 sqrt_n_list.append(math.sqrt(i)) # 绘制随机路径 plt.plot(listx, listy) plt.xlabel("X轴位置") plt.ylabel("Y轴位置") plt.title("2D随机步路径可视化") plt.show() # 绘制总路程与√n的关系(此时总路程和n线性,和√n二次,符合预期) plt.plot(sqrt_n_list, total_distance_list) plt.xlabel("步数的平方根(√n)") plt.ylabel("总路程") plt.title("总路程 vs √n") plt.show() # 如果要验证位移和√n的线性关系,计算每一步的位移并绘制 displacement_list = [math.sqrt(x_pos**2 + y_pos**2) for x_pos, y_pos in zip(listx, listy)] plt.plot([math.sqrt(i) for i in range(n+1)], displacement_list) plt.xlabel("步数的平方根(√n)") plt.ylabel("位移(到原点的距离)") plt.title("位移 vs √n") plt.show()
总结
- 代码错误:总路程的计算逻辑错误,误将位置到原点的距离累加,而非每一步的步长。
- 理论误解:混淆了「总路程」和「位移」的概念,随机步的线性关系结论针对的是位移的均方值,而非总路程。
内容的提问来源于stack exchange,提问作者Belal Bahaa
相关产品推荐
相关产品推荐

