Php – how to calculate angle between two vectors code in php

linear-algebramathPHP

I want to find the angle between the vector

v1 = [-1,-2]

and

v2 = [90,-5]

here solution given how to calculate angle (mathematics)

in php code need to calculate angle between two vector [-1,-2] and [90,-5].
Need php code.

Thanks

Best Answer

function norm($vec)
{
    $norm = 0;
    $components = count($vec);

    for ($i = 0; $i < $components; $i++)
        $norm += $vec[$i] * $vec[$i];

    return sqrt($norm);
}

function dot($vec1, $vec2)
{
    $prod = 0;
    $components = count($vec1);

    for ($i = 0; $i < $components; $i++)
        $prod += ($vec1[$i] * $vec2[$i]);

    return $prod;
}

And to calculate the actual angle:

$v1 = array(-1, -2);
$v2 = array(90, -5);

$ang = acos(dot($v1, $v2) / (norm($v1) * norm($v2)));

echo $ang; // angle in radians
> 1.97894543055