如何使 php cos 函数返回正确的值?
我已经尝试过,
$x = cos(deg2rad($angle));
但当角度为 90 度而不是 0 时,它会返回 6.12323399574E-17。 我读到这是一个浮点问题,但是有解决方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
无论如何,6.1E-17几乎为零[*]。如果您需要实际将结果与零进行比较,在浮点数学中,您应该检查它是否在所需值的一定容差范围内,因为大多数数字无法正确表示。
当然,严格来说,零实际上是一个可以用浮点正确表示的数字。真正的问题是
pi / 2.0
不可能,因此cos
函数的输入不“正确”。[*] 结合上下文来看,以 1 AU(太阳到地球的平均距离)的比例计算,它相当于 0.0092 毫米,或大约 人类头发平均宽度的十分之一...
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.
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 yourcos
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...
6.12323399574E-17 是一个非常小的浮点数(小数点后 17 个零,后跟 6),几乎与 0 没有区别。如果您正在处理浮点(任何余弦函数都必须如此),您将无法避免问题像这样。如果需要将浮点数与零进行比较,则必须使用误差线(即该数字是否在零附近的某个值范围内),而不是绝对比较,即使使用比余弦更简单的函数也是如此。如果您只需要对结果进行一些数学运算(加,乘,等等),它的表现几乎与零完全相同,因此您无需担心。
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.
试试这个
Try this