tags:

views:

92

answers:

2
>     if (((test>=0) && (test<=90)) || ((test>270) && (test<=360))){n_y=1;}
>     else {n_y=-1;}

I need the magnitude of trigonometric function in order to determine the sign of the trigonometric function for an angle falling into a particular quadrant.

My plan is to replace the code above with something equivalent.

Here is what I want to do in pseudo-code.

n_y = cos(test) / (magnitude of cos (test)); 

This will give me same thing. Abs() only takes integers. Any help is appreciated.

+2  A: 

I don't know what Abs() you're using, fabs from the C++ standard takes doubles just fine.

But you don't really want magnitude, because then you're stuck doing an expensive division.

Instead just use a signum function.

Ben Voigt
Brilliant! no signum in C++, but the link led me to copysignWhich does the above in one line:n_y=copysignf(1, cos(angle));
seaworthy
@seaworthy: `copysign` is nonstandard.
Potatoswatter
@potatoswatter: it's part of math.h, isn't that a standard?
seaworthy
@seaworthy: It's standard C99 but not standard C++.
Potatoswatter
If not being standard C++ bothers you, the answers to the question I linked to supply several other ways of implementing signum. Of course, the original code is much faster than the new code calling `cos`, but didn't handle non-canonical angles. I'd think that modulo would still be faster though.
Ben Voigt
A: 

Did you #include <cmath> to get the floating-point overloads for abs?

As for finding the quadrant, if 0 <= test <= 360, and you want to test 90 < test <= 270 just use 90 < test && test <= 270. There is a continuous range between the two discontinuous ranges you are currently testing. However, your particular example defines things asymmetrically as it maps 0 => 1 and 270 => -1.

Potatoswatter