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

后端 未结 3 946
情深已故
情深已故 2021-01-19 01:50

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 fl

3条回答
  •  余生分开走
    2021-01-19 02:35

    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...

提交回复
热议问题