javascript 为什么 Math.cos(90 * Math.PI/180) 产生 6.123031769111... 而不是零?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9652695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Math.cos(90 * Math.PI/180) yield 6.123031769111... and not zero?
提问by Sean
I convert degrees to radians (degrees * Math.PI/180) but why does the following:
我将度数转换为弧度(度数 * Math.PI/180),但为什么会出现以下情况:
Math.cos(90 * Math.PI/180)
yield 6.123031769111... and not zero?
产量 6.123031769111... 而不是零?
I'm trying to perform 2D rotations uses matrixes and the results are completely out of whack.
我正在尝试使用矩阵执行 2D 旋转,结果完全不正常。
回答by templatetypedef
The output of
的输出
Math.cos(90 * Math.PI/180)
is
是
6.123031769111886e-17
Notice the e-17
at the end, which means that this number is 6.123 x 10-17. This is a number so vanishingly close to 0 that it's effectively 0. The reason that it's not identically 0 is due to rounding errors in the IEEE-754 double format which prevents you from getting an exact representation of π / 2 and causes minute rounding errors in the calculation of the cosine.
注意e-17
末尾的 ,这意味着这个数字是 6.123 x 10 -17。这是一个非常接近 0 的数字,实际上是 0。它不是完全相同的 0 的原因是由于 IEEE-754 双精度格式中的舍入错误,这会阻止您获得 π / 2 的精确表示并导致微小的舍入错误在余弦的计算中。
By the way - I was pretty surprised as well when the result came back starting with a 6! It's only after I looked at the very end that things started to make sense.
顺便说一句 - 当结果以 6 开始返回时,我也很惊讶!直到我看到最后,事情才开始变得有意义。
Hope this helps!
希望这可以帮助!
回答by Karl Knechtel
6.123233995736766e-17
is scientific notation for a very small number, close to zero. It is not exactly zero because of rounding errors and so forth.
是一个非常小的数字的科学记数法,接近于零。由于舍入误差等原因,它不完全为零。
回答by Billjk
6.123233995736766e-17 is very very close to zero. Just round the number.
6.123233995736766e-17 非常非常接近于零。只需将数字四舍五入即可。