Completed
Push — dev ( 80a148...4ac9b0 )
by Jordan
03:47
created

CartesianCoordinate::distanceTo()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 28
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 28
rs 8.5806
cc 4
eloc 16
nc 4
nop 1
1
<?php
2
3
namespace Samsara\Fermat\Values;
4
5
use Samsara\Exceptions\UsageError\IntegrityConstraint;
6
use Samsara\Fermat\Numbers;
7
use Samsara\Fermat\Types\Tuple;
8
use Samsara\Fermat\Values\Base\CoordinateInterface;
9
10
class CartesianCoordinate extends Tuple implements CoordinateInterface
11
{
12
13
    public function distanceTo(CoordinateInterface $coordinate): ImmutableNumber
14
    {
15
        if (!($coordinate instanceof CartesianCoordinate)) {
16
            throw new IntegrityConstraint(
17
                'Must be the same coordinate system',
18
                'Only attempt to get distance between coordinates that use the same coordinate system',
19
                'Distance cannot be calculated between coordinates that use different coordinate systems because the properties necessary to convert them cannot be assumed'
20
            );
21
        }
22
23
        if ($this->size() != $coordinate->size()) {
24
            throw new IntegrityConstraint(
25
                'Must have same dimensionality',
26
                'Check dimensionality of both coordinates before getting distance',
27
                'Coordinates must share the same number of axes in order for a distance to be calculated'
28
            );
29
        }
30
31
        $n = Numbers::makeZero();
32
33
        foreach ($this->all() as $index => $value) {
34
            $n = $n->add($coordinate->get($index)->subtract($value)->pow(2));
35
        }
36
37
        $n = $n->sqrt();
38
39
        return $n;
40
    }
41
42
}