Math.cos inaccurancy

前端 未结 3 1925
野性不改
野性不改 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@

提交回复
热议问题