找到最近邻居的最终代码问题

问题描述

在寻找点位置之间的最近邻居距离时,我需要此代码的帮助。我认为问题在于,只有在小于最近的“ newdistance”的情况下,才将“ nearestdistance”添加到“ Sumdistance”,而不是添加最近的距离。虽然我可能是错的。代码如下所示:

q = loadPoints(f)

n = 1416
Sumdistance = 0

for i in q:
    iID = int(i.getID())
    x1 = float(i.getX())
    y1 = float(i.getY())
    nearestdistance = 999999999999999999999999999
    for j in range(0,n):
        if j != iID:
            jID = (q[j].getID())
            x2 = float(q[j].getX())
            y2 = float(q[j].getY())
            dx = x1 - x2
            dy = y1 - y2
            newdistance = math.sqrt(math.pow(dx,2) + (math.pow(dy,2)))
                                
            if newdistance < nearestdistance:
                nearestdistance = newdistance
                else nearestdistance = 
                
    Sumdistance = Sumdistance + nearestdistance
    
area = 10000000000
Do = Sumdistance/n
De = 0.5/(math.sqrt(n/area))
ANN = Do/De
print(ANN)

谢谢!

解决方法

您是正确的-迭代邻居后,应始终将nearestdistance添加到Sumdistance

for i in q:
    ......
    for j in range(0,n):
        if j != iID:
            ........
                                
            if newdistance < nearestdistance:
                nearestdistance = newdistance
                
    Sumdistance += nearestdistance

请注意,最终的总和将包括反向邻居,即a -> bb -> a