Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stable Cotangent

Tags:

Is there a more stable implementation for the cotangent function than return 1.0/tan(x);?

like image 523
Meh. Avatar asked Sep 17 '10 19:09

Meh.


1 Answers

cot(x) = cos(x)/sin(x) should be more numerically stable close to π/2 than cot(x) = 1/tan(x). You can implement that efficiently using sincos on platforms that have it.

Another possibility is cot(x) = tan(M_PI_2 - x). This should be faster than the above (even if sincos is available), but it may also be less accurate, because M_PI_2 is of course only an approximation of the transcendental number π/2, so the difference M_PI_2 - x will not be accurate to the full width of a double mantissa -- in fact, if you get unlucky, it may have only a few meaningful bits.

like image 59
zwol Avatar answered Sep 20 '22 04:09

zwol