我如何使PHP的COS功能返回正确的价值? [英] How can i make the php cos function return the correct value?

查看:437
本文介绍了我如何使PHP的COS功能返回正确的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

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

但是当角度为90度而不是0时,它返回6.12323399574E-17。
我读了这是一个浮点问题,但是有一个解决方法?

解决方案

6.1E-17几乎是零[*]。如果您需要实际比较结果为零,在浮点数学中,您应该检查它是否在所需值的某个容差范围内,因为大多数数字无法正确表示。

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

严格来说,零实际上是一个可以 的数字在浮点上正确表示。真正的问题是 pi / 2.0 不能这样,所以 cos 函数的输入不是正确的。

[*]为了说明这一点,以1 AU(从太阳到地球的平均距离)的比例来看,相当于0.0092 毫米,或者关于人发的平均宽度的十分之一 ...


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?

解决方案

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

这篇关于我如何使PHP的COS功能返回正确的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆