无法理解为什么我的php余弦相似性代码无法正常工作

时间:2019-09-01 00:57:04

标签: php

我正在为我的朋友的游戏氏族建立一个网站。我正在尝试使用一个PHP代码来获取玩家的坐标,在一些已知位置上循环并打印最近位置的名称。

但是我无法正常工作。似乎总是要打印“ Balota”,它是数组中的索引1。我还注意到余弦函数不能工作,因为所有值都大于1.0。

但是我现在完全被困住了。我想我已经在它上面跳了太久了,它的位置就在我眼前,但是我看不到它。

<?php


function DotProd($loc1,$loc2){
    return array_sum(array_map(create_function('$a, $b', 'return $a * $b;'), $loc1, $loc2));
}
function CosineSim($loc1,$loc2){
    return DotProd($loc2,$loc2)/sqrt(DotProd($loc1,$loc2)*DotProd($loc1,$loc2));
}
function Closest($loc){
    $novo = array(11300,14300);
    $balota = array(4500,2500);
    $zelen = array(2500,5200);
    $sever = array(7900,12600);
    $vybor = array(4500,8200);
    $nwaf = array(4500,10200);
    $neaf = array(12100,12500);
    $kamensk = array(7870,14600);
    $bere = array(12900,10000);
    $gorka = array(9600,8900);
    $elektro = array(10100,2000);
    $cherno = array(6600,2600);
    $stary = array(6100,7700);
    $novy = array(7000,7700);
    $mysk = array(1100,7200);

    $locations = array($novo,$balota,$zelen,$sever,$vybor,$nwaf,$neaf,
        $kamensk,$bere,$gorka,$elektro,$cherno,$stary,$novy,$mysk);

    $sim = 99999999999;
    $locat = 0;
    for($i = 14; $i >= 0; $i--){
        $s = CosineSim($loc,$locations[$i]);
        echo    "<br>" . $i . " " . CosineSim($loc,$locations[$i]);
        if($s < $sim){
            $sim = $s;
            $locat = $i;
        }
    }
    $items = array("Novo","Balota","Zelenogorsk","Severograd","Vybor","NWAF","NEAF","Kamensk Military","Berezino",
                        "Gorka","Elektro","Cherno","Stary Sobor","Novy Sobor","Myshkino");
    return $items[$locat];
}
$x = $_GET["xpos"];
$y = $_GET["ypos"];


$location = array($x,$y);


echo "<b>You are at " . $x . ":" . $y; 
$index = Closest($location);
echo "<br>You're pretty close to ". $index . "<br>";

?>

1 个答案:

答案 0 :(得分:0)

我正在使用基于以下链接的距离计算公式:https://www.mathwarehouse.com/algebra/distance_formula/index.php

我只更改了CosineSim。其余代码保持不变。而且您实际上不需要DotProd。它不优雅,但对我有用。

function CosineSim($loc1,$loc2){
    // sum of x coordinates
    $x1 = ($loc1[0]-$loc2[0])*($loc1[0]-$loc2[0]);

    // sum of y coordinates
    $y2 = ($loc1[1]-$loc2[1])*($loc1[1]-$loc2[1]);

    $summ = $x1 + $y2;
    $sqrt_res = sqrt($summ);
    return $sqrt_res;
}

如果我输入类似的内容:

You are at 4640:7205
...
You're pretty close to Vybor

希望这会有所帮助!