How can i make the php cos function return the cor

2019-02-22 17:31发布

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?

3条回答
劫难
2楼-- · 2019-02-22 18:27

Try this

$x = round(cos(deg2rad($angle)), 3);
查看更多
来,给爷笑一个
3楼-- · 2019-02-22 18:28

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-22 18:36

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

查看更多
登录 后发表回答