我想编写一个python脚本来生成均匀分布的3D坐标(例如x,y,z),其中x,y和z为0到1之间的浮点数。目前,z可以固定,因此我需要的是2D(xy)平面中的均匀分布点。我写了一个脚本来完成这项工作,并检查了x和y都是统一数字。但是,我不确定这些点是否在(x-y)平面中均匀分布。
我的代码是
1 import matplotlib.pyplot as plt
2 import random
3 import numpy as np
4 import csv
5 nk1=300
6 nk2=300
7 nk3=10
8 kx=[]
9 ky=[]
10 kz=[]
11 for i in range(nk1):
12 for j in range(nk2):
13 for k in range(nk3):
14 xkg1=random.random()
15 xkg2=random.random()
16 xkg3 = float(k)/nk3
17 kx.append(xkg1)
18 ky.append(xkg2)
19 kz.append(xkg3)
20 kx=np.array(kx)
21 count, bins, ignored = plt.hist(kx, normed=True)
22 plt.plot(bins, np.ones_like(bins), linewidth=2, color='r')
23 plt.show()
该图显示“ kx”和“ ky”都是均匀分布的数字,但是,如何确定x-y在2D平面中均匀分布?
答案 0 :(得分:1)
就像使用np.histogram
1 在1D中检查均匀性一样,您可以使用np.histogram2d
在2D中进行相同的操作,并使用np.histogramdd
在3D +中进行相同的操作
要查看示例,让我们首先通过消除循环来修复循环:
kx = np.random.random(nk1 * nk2 * nk3)
ky = np.random.random(nk1 * nk2 * nk3)
kz = np.tile(np.arange(nk3) / nk3, n1 * n2)
hist2d, *_ = np.histogram2d(kx, ky, range=[[0, 1], [0, 1]])
range参数可确保您在各个方向上对[0,1)进行装仓,而不考虑数据的实际最小和最大值,无论距离有多近。
现在,如何可视化hist2d
中的100个数据点完全取决于您。一种简单的方法是像处理一维情况一样,将其撕开并制作条形图:
plt.bar(np.arange(hist2d.size), hist2d.ravel())
plt.plot([0, hist2d.size], [nk1 * nk2 * nk3 / hist2d.size] * 2)
另一种简单的方法是进行heat map:
plt.imshow(hist2d, interpolation='nearest', cmap='hot')
实际上,它不如条形图有用,也不能推广到更大的尺寸。
您最好的选择可能只是检查原始数据的标准偏差。
1 或者更确切地说,plt.hist
为您提供了帮助。
答案 1 :(得分:0)
在@Mad Physicist的帮助下,我终于找到了一种方法来验证2D中随机数的均匀分布。在这里,我发布了我的脚本,并解释了细节:
1 import numpy as np
2 import random
3 import matplotlib.pyplot as plt
4 import matplotlib
5 fig = plt.figure()
6 ax1 = fig.add_subplot(211)
7 ax2 = fig.add_subplot(212)
8 nk=100
9 nk=100
10 nk=1
11 kx1=[]
12 ky1=[]
13 kz1=[]
14 for i in range(nk1):
15 for j in range(nk2):
16 for k in range(nk3):
17 xkg =r andom.random()
18 ykg = random.random()
19 zkg = float(k)/nk3
20 kx.append(xkg)
21 ky.append(ykg)
22 kz.append(zkg)
23 kx=np.array(kx)
24 ky=np.array(ky)
25 kz=np.array(kz)
26 xedges, yedges = np.linspace(0, 1, 6), np.linspace(0, 1, 6)
27 ## count the number of poins in the region definded by (xedges[i],
xedges[i+1])
28 ## and (yedges[i], xedges[y+1]). There are in total 10*10 2D
squares.
29 hist, xedges, yedges = np.histogram2d(kx, ky, (xedges, yedges))
30 xidx = np.clip(np.digitize(kx, xedges) - 1, 0, hist.shape[0] - 1)
31 yidx = np.clip(np.digitize(ky, yedges) - 1, 0, hist.shape[1] - 1)
32 ax1.bar(np.arange(hist.size),hist.ravel())
33 ax1.plot([0,hist.size], [nk1 * nk2 * nk3 / hist.size] * 2)
34 c = hist[xidx, yidx]
35 new = ax2.scatter(kx, ky, c=c, cmap='jet')
36 cax, _ = matplotlib.colorbar.make_axes(ax2)
37 cbar = matplotlib.colorbar.ColorbarBase(cax, cmap='jet')
38 ax2.grid(True)
39 plt.show()