在数组中查找不等于给定点的最近点
Finding nearest point in an array that is not equal to given point
我有一个点和一组值。我希望在数组中找到最近的点 y,使 x != y。目前我在 Python 中使用标准的 Scipy KDTree 方法,但这并不仅仅考虑唯一点。是否有任何解决方法或是否需要手动实施?谢谢!
二维数组解法:
我回收了大部分与以前相同的方法,但这次它应该适用于您的结构
import math
X = [0,0] # Your cooridinate
x1 = X[0]
y1= X[1]
array = [[1,1],[0,1],[1,0],[-2,2]] # Sample array of data
smallestDistance = 9999 # Make it big so it can be replaced immediately, essentially just a placeholder
for point in array:
x2 = point[0]
y2 = point[1]
separation = math.hypot(x2 - x1, y2 - y1) #Distance equation in easy format
if separation < smallestDistance and separation!=0: # Could make this <= instead of < if you want to replace any ties for closest point
smallestDistance = separation
closestPoint = point
print(f"Nearest cooridinate = {closestPoint}, separation from {X} is: {smallestDistance}")
一维数组的旧解决方案:
我不太确定你的数组结构是什么,但据我所知你有一个一维数组和一个给定的值;您希望数组中最接近原始值的唯一值。如果这是正确的,那么快速而肮脏的解决方案可能类似于:
smallestDifference = 99999999 #Make this some large number
y = array[someindex]
for thing in array:
difference = abs(thing-y)
if difference<smallestDifference & difference != 0: #Must be closer than the last recorded closest point, AND non-zero i.e. a unique point
smallestDifference = difference #New smallest distance between points
closestPoint = thing #Record the new closest point
print(f"x = {closestPoint}, |y-x| = {smallestDifference}")
如果这是一个 >1d 数组可能会有点棘手并且可能不是最快的解决方案,因为它必须检查每个点..但可能会完成工作:-)
我有一个点和一组值。我希望在数组中找到最近的点 y,使 x != y。目前我在 Python 中使用标准的 Scipy KDTree 方法,但这并不仅仅考虑唯一点。是否有任何解决方法或是否需要手动实施?谢谢!
二维数组解法: 我回收了大部分与以前相同的方法,但这次它应该适用于您的结构
import math
X = [0,0] # Your cooridinate
x1 = X[0]
y1= X[1]
array = [[1,1],[0,1],[1,0],[-2,2]] # Sample array of data
smallestDistance = 9999 # Make it big so it can be replaced immediately, essentially just a placeholder
for point in array:
x2 = point[0]
y2 = point[1]
separation = math.hypot(x2 - x1, y2 - y1) #Distance equation in easy format
if separation < smallestDistance and separation!=0: # Could make this <= instead of < if you want to replace any ties for closest point
smallestDistance = separation
closestPoint = point
print(f"Nearest cooridinate = {closestPoint}, separation from {X} is: {smallestDistance}")
一维数组的旧解决方案: 我不太确定你的数组结构是什么,但据我所知你有一个一维数组和一个给定的值;您希望数组中最接近原始值的唯一值。如果这是正确的,那么快速而肮脏的解决方案可能类似于:
smallestDifference = 99999999 #Make this some large number
y = array[someindex]
for thing in array:
difference = abs(thing-y)
if difference<smallestDifference & difference != 0: #Must be closer than the last recorded closest point, AND non-zero i.e. a unique point
smallestDifference = difference #New smallest distance between points
closestPoint = thing #Record the new closest point
print(f"x = {closestPoint}, |y-x| = {smallestDifference}")
如果这是一个 >1d 数组可能会有点棘手并且可能不是最快的解决方案,因为它必须检查每个点..但可能会完成工作:-)