Math.cos inaccurancy

前端 未结 3 1837
野性不改
野性不改 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:47

    Comparing calculated floating point numbers for equality is almost always a bad idea, since (as others have stated) they are approximations, and errors appear.

    Instead of checking for a==b, check for equality to within a threshold that makes sense for your application, as with Math.abs(a-b) < .00001. This is good practice in any programming language that represents numbers as floating point values.

    If you're storing integers in floating point variables and just adding, subtracting, and multiplying, they'll stay integers (at least until they go out of bounds). But dividing, using trig functions, etc., will introduce errors that must be allowed for.

    -m@

    0 讨论(0)
  • 2021-01-20 01:51

    Math.PI/2 is an approximation of the real value of pi/2. Taking the exact cosine of this approximated value won't yield zero. The value you get is an approximation of this exact value up to the precision of the underlying floating point datatype.

    Using some arbitrary precision library, you can evaluate the difference between pi/2 in double precision and the exact value to

     0.0000000000000000612323399573676588613032966137500529104874722961...
    

    Since the slope of the cosine close to its zeros is 1, you would expect the cosine of the approximation of pi/2 to be approximately equal to this difference, and indeed it is.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题