Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i make the php cos function return the correct value?

I've tried

$x = cos(deg2rad($angle));

but it returns 6.12323399574E-17 when the angle is 90 degrees instead of 0. I read that this is a floating point problem, but is there a workaround?

like image 678
Keeper Hood Avatar asked Jun 05 '11 14:06

Keeper Hood


2 Answers

6.1E-17 is almost zero anyway[*]. If you need to actually compare the result to zero, in floating point math you should check that it's within a certain tolerance of the desired value, since most numbers can't be represented correctly.

$x = cos(deg2rad($angle));
$is_zero = (abs($x) < 1e-10);

Strictly speaking, of course, zero is actually a number that can be represented correctly in floating point. The real problem is that pi / 2.0 can't be, so the input to your cos function isn't "correct".

[*] To put that in context, taken as a proportion of 1 AU (the average distance from the Sun to the Earth) it is equivalent to 0.0092 millimeters, or about a tenth of the average width of a human hair...

like image 77
Alnitak Avatar answered Oct 20 '22 23:10

Alnitak


6.12323399574E-17 is an extremely small floating point number (17 zeros after the decimal point followed by a 6), almost indistinguishable from 0. If you are dealing with floating points (as any cosine function must), you can't avoid issues like this. If you need to compare a floating point number to zero, you must do it with error bars (i.e. is this number within a certain range of values around zero), not absolute comparison, even with simpler functions than cosine. If you just need to do some math with the result (add it, multiply it, whatever), it will behave almost exactly like zero so you won't need to worry.

like image 43
Shea Levy Avatar answered Oct 20 '22 23:10

Shea Levy