python代码:
from random import uniform
from math import sqrt
import numpy as np
testTimeList = [100,1000,10000,100000,1000000]
for nTest in testTimeList:
lenRecords = []
for i in xrange(nTest):
x1 = [uniform(0,1),uniform(0,1)]
x2 = [uniform(0,1),uniform(0,1)]
d = sqrt((x1[0]-x2[0])**2.0+(x1[1]-x2[1])**2.0)
lenRecords.append(d)
avgLen = np.mean(lenRecords)
print("样本个数: %8d 平均距离: %.4f" %(nTest,avgLen))
运行结果:
样本个数: 100 平均距离: 0.5346
样本个数: 1000 平均距离: 0.5200
样本个数: 10000 平均距离: 0.5253
样本个数: 100000 平均距离: 0.5221
样本个数: 1000000 平均距离: 0.5216