2016-04-11 19:35:17 +00:00
|
|
|
<?php
|
|
|
|
|
2016-11-20 21:53:17 +00:00
|
|
|
declare(strict_types=1);
|
2016-04-11 19:35:17 +00:00
|
|
|
|
2016-04-20 21:56:33 +00:00
|
|
|
namespace Phpml\Math\Distance;
|
2016-04-11 19:35:17 +00:00
|
|
|
|
|
|
|
use Phpml\Exception\InvalidArgumentException;
|
2016-04-20 21:56:33 +00:00
|
|
|
use Phpml\Math\Distance;
|
2016-04-11 19:35:17 +00:00
|
|
|
|
|
|
|
class Euclidean implements Distance
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @param array $a
|
|
|
|
* @param array $b
|
|
|
|
*
|
|
|
|
* @return float
|
|
|
|
*
|
|
|
|
* @throws InvalidArgumentException
|
|
|
|
*/
|
|
|
|
public function distance(array $a, array $b): float
|
|
|
|
{
|
|
|
|
if (count($a) !== count($b)) {
|
2016-04-18 20:58:43 +00:00
|
|
|
throw InvalidArgumentException::arraySizeNotMatch();
|
2016-04-11 19:35:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
$distance = 0;
|
|
|
|
|
2017-02-09 09:30:38 +00:00
|
|
|
foreach ($a as $i => $val) {
|
|
|
|
$distance += ($val - $b[$i]) ** 2;
|
2016-04-11 19:35:17 +00:00
|
|
|
}
|
|
|
|
|
2016-05-02 21:36:58 +00:00
|
|
|
return sqrt((float) $distance);
|
2016-04-11 19:35:17 +00:00
|
|
|
}
|
|
|
|
}
|