我不明白,为什么我在JavaScript中从三角函数中得到一些非常奇怪的值。例如:
Math.sin(Math.PI); // returns 1.2246467991473532e-16, but should return 0
Math.cos(Math.PI/2); // returns 6.123233995736766e-17, but should return 0
Math.sin(3.14); // returns 0.0015926529164868282, whitch is ok but
Math.sin(3.141592); // returns 6.535897930762419e-7!
我在Mozilla和Chrome中尝试了这个并得到了相同的结果。似乎三角函数的参数太精确了。
请帮忙!
你可以使用Number.EPSILON
Number.EPSILON
属性表示1与大于1的最小浮点数之间的差异。
并取值和期望值的绝对值,并检查它是否小于Number.EPSILON
。如果true
,那么值的误差小于浮点运算的可能误差。
console.log([
[Math.sin(Math.PI), 0],
[Math.cos(Math.PI/2), 0],
[Math.sin(3.14), 0.0015926529164868282],
[Math.sin(3.141592), 6.535897930762419e-7]
].map(([a, b]) => Math.abs(a - b) < Number.EPSILON));
还有一些关于浮点值的有限数字表示的问题: