JavaScript floating point precision issue

2019-09-11 13:12发布

问题:

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);