2013-04-21 75 views
0

我正在尝试编写一个方法,该方法将返回距离3D空间中另一个点最近的点的索引。这些点存储在KD树中,我将它们与作为我的方法参数的点p进行比较。下面是方法:查找具有特定距离的第一个元素

public int NearestPointWithDistance(KDnnTreeNode node, Point p, Double distance){ 
    int index = -1; 
    if(node == null){ 
    return -1; 
    }else{ 
     double[] point_coordinates = data[node.eltIndex]; 
     Point q = new Point(point_coordinates[0],point_coordinates[1], point_coordinates[2]); 
     if(KDnnTree.distance(p, q) == distance){ 
      return index; 
     } 

     if(node.left != null){ 
      final int left_child = NearestPointWithDistance(node.left, p, distance); 
     } 
     if(node.right != null){ 
      final int right_child = NearestPointWithDistance(node.right, p, distance); 
     } 
    } 
    return index; 

}

的问题是,可能有多个百分点的距离相同。我得到的结果是点的索引列表(见下文),但我只想要列表的第一个元素(在下面的例子中,这将是数字54510)。

54510 
54511 
54512 
54514 
54518 
54526 
54543 
54577 
65355 
76175 
54482 
54416 
54278 
21929 
54001 
74323 

我知道这不是在KD树中搜索两个关闭点的方法,但我想先尝试这种方法。

+0

你需要比较来自左和右的结果,只需要一个。 – BobTheBuilder 2013-04-21 09:15:09

回答

0

请勿使用java.lang.Double作为参数。使用double

原因是,如果您的KDNTree.distance()也将返回Double您将最终在比较对象的引用,而不是它们的值。

你有非常不方便的API。无论如何,让一个辅助函数:

public Point getNodePoint(Node node) 
{ 
    double[] point_coordinates = data[node.eltIndex]; 
    return new Point(point_coordinates[0],point_coordinates[1], point_coordinates[2]); 
} 

使用最佳距离availabale选择:

double result = KDnnTree.distance(p, q); 
if (result == distance) 
{ 
    return node.eltIndex; 
} 
index = node.eltIndex; // assume given node is best 
if (node.left != null) 
{ 
    final int left_child = NearestPointWithDistance(node.left, p, distance); 
    double left_distance = KDnnTree.distance(p, getNodePoint(left_child); 

    if (Math.abs(distance - result) > Math.abs(distance - left_distance)) 
    { 
     // result given is closer to wanted point 
     result = left_distance; 
     index = left_child; 
    } 
} 
if (node.right != null) 
{ 
    final int right_child = NearestPointWithDistance(node.right, p, distance); 
    double right_distance = KDnnTree.distance(p, getNodePoint(right_child); 

    if (Math.abs(distance - result) > Math.abs(distance - right_distance)) 
    { 
     // result given is closer to wanted point 
     result = right_distance; 
     index = right_child; 
    } 
} 
return index; 
相关问题