Robbie Robbie - 5 months ago 22
PHP Question

Calculating the sine of pi with php

I am trying to write a function to calculate the new x and y cooridinates after a rotation.
But for some reason it seems as though the sin function is not working as it should on a 180° angle:

$radians = deg2rad(180);
var_dump($radians);
$sin = sin($radians);
var_dump($sin);


Is there a workaround or something obvious I'm missing?

(The sin of pi should be 0).

Answer

The math functions use floating points. Because of the computational nature of floats, they have a few accuracy problems. The solution is to simply round your numbers:

$radians = deg2rad( 180 );
var_dump( $radians );

$sin = sin( $radians );
var_dump( round($sin, 3) );
Comments