Math.cos inaccurancy

前端 未结 3 1930
野性不改
野性不改 2021-01-20 01:08

alert(Math.cos(Math.PI/2));

Why the result is not exact zero? Is this inaccurancy, or some implementation error?

3条回答
  •  时光取名叫无心
    2021-01-20 01:58

    Floating-point numbers are normally approximations. Since floating-point numbers are represented in memory as binary numbers multiplied by an exponent only numbers that are sums of powers of 2 can usually be represented.

    Fractions such as 1/3 can't be written as a binary number and as such have no accurate floating-point representation. Even some numbers that can be written accurately in decimal, such as 0.1, can't be represented accurately in binary and so will not be represented correctly in floating point.

    PI is an irrational number and can't be represented as floating-point, so there will be rounding errors. Do not compare floating-point numbers for equality without including a tolerance parameter. This link has a good explanation of the basics.

提交回复
热议问题