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

僤鯓⒐⒋嵵緔 提交于 2019-12-04 03:28:47

问题


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?


回答1:


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




回答2:


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.




回答3:


Try this

$x = round(cos(deg2rad($angle)), 3);


来源:https://stackoverflow.com/questions/6243430/how-can-i-make-the-php-cos-function-return-the-correct-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!