我有两个坐标值。我正在计算每个坐标的欧几里德距离。我想在这里申请K-最近邻居算法。
选择最接近最大点的点(从所有点开始,选择最接近最大坐标数的点)
$result2 = mysqli_query($con,"SELECT pcount, ncount from test");
$result1 = mysqli_query($con,"SELECT pcount, ncount from test");
$i = 0;
$k = 0;
$min = 0;
while ($row1 = @mysqli_fetch_array($result1))
{
$pcount = $row1['pcount'];
$ncount = $row1['ncount'];
echo "pcount is $pcount<br/>";
echo "ncount is $ncount<br/></br>";
$a[$i] = $pcount ;
$b[$i] = $pcount ;
$j = 0;
$result2 = mysqli_query($con,"SELECT pcount, ncount from test");
while ($row2 = @mysqli_fetch_array($result2))
{
//echo "j is $j <br/>";
$a[$j] = $row2['pcount'];
$b[$j] = $row2['ncount'];
$diff = ($a[$i] - $a[$j])^2 + ($b[$i] - $b[$j])^2;
if( $diff != 0)
$diff = sqrt( $diff );
$j= $j + 1;
echo "$diff <br>";
arr[$k] = $diff;
$k = $k + 1;
}
//echo "i is $i <br/>";
$i = $i + 1;
}
此处,arr[$k]
包含所有点的距离差异。
如何获得最接近其他最大点的点数。可能有超过1个这样的点。
答案 0 :(得分:1)
我建议使用以下方法。
0)将db数据提取到2d数组中如下所示:
array(
array($x1,$y1),
array($x2,$y2),
...
)
1)构建数据,存储每个点到所有其他点的(方形)距离之和。
2)找到该数组中的最低值(最小值)。
3)获取具有该值的所有积分。
所以代码应如下所示:
// $a_points = array( array($x1,$y1), array($x2,$y2), ... ); // array of point coordinates
$a_sum_dists = array();
foreach ($a_points as $i => $pt1) {
list($x1, $y1) = $pt1;
$sum = 0;
foreach ($a_points as $j => $pt2) {
if ($j == $i) continue;
list($x2, $y2) = $pt2;
$sum += pow($x2- $x1, 2) + pow($y2- $y1, 2);
}
$a_sum_dists[$i] = $sum;
}
$min_sum = min($a_sum_dists);
$a_result_points = array_intersect_key(
$a_points,
array_filter($a_sum_dists, function ($v) use ($min_sum) {
return $v == $min_sum;
})
);