Inaccuracy Math.cos

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

Why is the result not an exact zero? Is this an inaccuracy or an implementation error?

+4
source share
3 answers

Math.PI/2 is an approximation of the actual value of pi/2 . Taking the exact cosine of this approximate value will not lead to zero. The value you get is an approximate value of this exact value to the accuracy of the underlying floating point data type.

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

  0.0000000000000000612323399573676588613032966137500529104874722961... 

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

+11
source

Floating-point numbers are usually approximations. Since floating point numbers are represented in memory, since binary numbers times the exponent, only numbers representing sums of degrees 2 can be represented.

Fractions such as 1/3 cannot be written as a binary number and as such do not have an exact floating point representation. Even some numbers that can be written exactly in decimal form, for example 0.1 , cannot be accurately represented in binary format and therefore will not display correctly in a floating point.

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

+2
source

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

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

If you store integers in floating point variables and just add, subtract and multiply, they will remain integers (at least until they go beyond). But division, the use of trigger functions, etc., will lead to errors that must be resolved.

-m @

0
source

Source: https://habr.com/ru/post/1348097/


All Articles