JavaScript floating point precision issue

隐身守侯 提交于 2019-12-12 05:28:46

问题


I am encountering a floating point precision issue, does anybody know why this happens? Why is it that the cosine function is affected, but not he sine function.

Math.sin(90 * Math.PI / 180);
// returned: 1, expected: 1

1 - Math.sin(90 * Math.PI / 180);
// returned: 0, expected: 0


Math.cos(90 * Math.PI / 180);
// returned: 6.123233995736766e-17, expected: 0

1 - Math.cos(90 * Math.PI / 180);
// returned: 0.9999999999999999, expected: 1

回答1:


The canonical answer to this one is What Every Computer Scientist Should Know About Floating-Point Arithmetic

With a little more trying you will find examples for "unexpected" results with the sine function.

E.g. Math.sin(180 * Math.PI / 180);



来源:https://stackoverflow.com/questions/34299407/javascript-floating-point-precision-issue

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