Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.cos inaccurancy

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

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

like image 364
Jan Turoň Avatar asked Dec 13 '22 14:12

Jan Turoň


2 Answers

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.

like image 112
Sven Marnach Avatar answered Dec 29 '22 05:12

Sven Marnach


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.

like image 41
sverre Avatar answered Dec 29 '22 04:12

sverre