Can cos (a) ever equal 0 in floating point

Given that PI / 2 can never be represented exactly at a floating point, is it safe to assume that cos (a) can never return an exact zero?

If so, then the following pseudo code will never go into the block (and it could be safely deleted):

... y = h/cos(a); if (!isfinite(a)) { // handle infinite y } 
+6
source share
3 answers

Zero is one of several values ​​that can be represented exactly. Many systems have a lookup table for common values ​​of sin and cos, so it is possible that you can return exactly zero result.

But you are safer using delta comparison before doing the division:

 if (Abs(cos(a)) < 0.0000001) { } 
+4
source

Besides zero, the double precision value, which is closest to the exact edge of Ο€ / 2, is 6381956970095103 * 2 ^ 797, which is equal to:

 (an odd integer) * Ο€/2 + 2.983942503748063...eβˆ’19 

Thus, for all double precision x values, we have the estimate:

 |cos(x)| >= cos(2.983942503748063...eβˆ’19) 

Note that this is a limitation on the mathematically accurate value, and not on the value returned by the cos library function. On a platform with a high-quality math library, this estimate is good enough, and we can say that cos(x) not zero for any double precision x . In fact, it turns out that this is not the only double; this property holds for all major IEEE-754 types if cos exactly rounded.

However, this does not mean that this can never happen on a platform that had a spectacularly low implementation of the reduction of trigonometric arguments.

More importantly, in your example, y can be infinite without cos(a) equal to zero:

 #include <math.h> #include <stdio.h> int main(int argc, char *argv[]) { double a = 0x1.6ac5b262ca1ffp+849; double h = 0x1.0p1022; printf("cos(a) = %g\n", cos(a)); printf("h/cos(a) = %g\n", h/cos(a)); return 0; } 

compile and run:

 scanon$ clang example.c && ./a.out cos(a) = -4.68717e-19 h/cos(a) = -inf 
+7
source

no, this cannot be guaranteed, because cos itself is calculated with an error, so its value can be an exact zero quite easily.

0
source

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


All Articles