Skip to content

Instantly share code, notes, and snippets.

@arbennett
Last active September 12, 2017 04:17
Show Gist options
  • Save arbennett/fdb93b9e3977fa39d2670179813505ae to your computer and use it in GitHub Desktop.
Save arbennett/fdb93b9e3977fa39d2670179813505ae to your computer and use it in GitHub Desktop.
var
x : array[0..99] of single;
y : array[0..99] of single;
i : Integer;
N : Integer;
s : Integer;
nn : Integer;
x_s : single;
y_s : single;
x_dist : single;
y_dist : single;
dist : single;
nearest_dist : single;
nearest_idx : Integer;
begin
N := 100;
// initialize coordinates
for i := 1 to N do
begin
x[i] := Random;
y[i] := Random;
end;
// find nearest neighbor of one
s := Random(N);
x_s := x[s];
y_s := y[s];
nearest_dist := 10;
for i := 1 to N do
begin
if i <> s then
begin
x_dist := x_s - x[i];
y_dist := y_s - y[i];
dist := Sqrt(x_dist*x_dist + y_dist*y_dist);
if nearest_dist > dist then
begin
nearest_dist := dist;
nearest_idx := i;
end;
end;
end;
end.
#!/usr/bin/env python
import numpy as np
import scipy.spatial as sp
def main():
N = 10
x = np.random.random((N, 2))
tree = sp.cKDTree(x)
for i in range(N):
dist, idx = tree.query(x[i], k=2, distance_upper_bound=4)
print(dist[-1], idx[-1])
if __name__ == '__main__':
main()
@arbennett
Copy link
Author

0.165303482593 6                 
0.232515858306 4                 
0.218432027652 9                 
0.17886330167 8                  
0.171672012593 0                 
0.451214834747 2                 
0.165303482593 0                 
0.316582339776 6                 
0.17886330167 3                  
0.218432027652 2 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment