我不明白,为什么我会从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中尝试了一下,得到了同样的结果。三角函数的参数似乎太精确了。
请帮帮我!
发布于 2017-12-18 22:52:42
您可以使用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));
有关浮点值的有限数字表示问题的更多信息:
https://stackoverflow.com/questions/47870700
复制相似问题