Why didn't I get tan(PI /2) = infinty in C

When I calculate tan(PI/2) I get -22877332 in c, but tan(Pi/2) is infinity. and google giving it as 3060023.30695 Why i am getting different answer

I tried on mingw compiler and in google both are giving different answer

float32 Tan_f32 (float32 ValValue ) { float32 Result_Val; Result_Val= (tanf(ValValue)); return Result_Val; } 

in mingw compiler it gives -22877332 and in google 3060023.30695

4

2 Answers

It is impossible to pass π/2 to tan or tanf because π is irrational, so any floating-point number, no matter how precise, will be at least slightly different from π/2. Therefore, tanf(ValValue) returns the tangent of some value close to π/2, and that tangent is large but not infinite.

In the common format used for float, IEEE-754 basic 32-bit binary floating-point, the closest representable number to π/2 is 1.57079637050628662109375. The tangent of that number is approximately −22877332.4289, and the closest value representable in float is −22877332, which is the result you got. So your tanf is giving you the best possible result for the input number you gave it.

7

The C standard, or indeed the common but by no means ubiquitous IEEE754 floating point standard, give no guarantee of the accuracy of tan (Cf sqrt). An implementation will make a compromise in getting a good result out in a reasonable number of clock cycles.

In particular, the behaviour of the trigonometric function near an asymptote is particularly unpredictable; and that's the case here.

Accepting that the fault is not due to your value of pi (worth a check although note that because pi is transcendental it can't be represented exactly in any floating point system), if you want a well-behaved tan function across the whole domain, you'll be better off using a third party mathematics library.

Finally, note that under IEEE754, you might get more consistent behaviour around an asyptote if you let floating point division deal with the pole, and use

double c = cos(x); tan(x) = sqrt(1 / c / c - 1); 

This might be more numerically stable, as IEEE754 defines a division by zero.

5

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like