JavaScript浮点精度问题 [英] JavaScript floating point precision issue

查看:75
本文介绍了JavaScript浮点精度问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到浮点精度问题,有人知道为什么会这样吗?为什么余弦函数会受到影响,而正弦函数却没有受到影响.

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

推荐答案

对此的典型答案是再进行一些尝试,您将发现使用正弦函数获得意外"结果的示例.

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

例如Math.sin(180 * Math.PI / 180);

这篇关于JavaScript浮点精度问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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