direction component of vector without case analysis

Vector related question here - mostly out of curiousity: Is there a way, starting with a vector in component form (<x, y>) to get the direction angle in [0, 2 * pi) without using case analysis based on the quadrant the vector is in? In a programming project I wanted to write a function that pulls out the direction angle, in radians, from a vector in component form. So I wrote this:

Code:

`vectorDirection :: (Double, Double) -- vector`

-> Double -- angle in radians

vectorDirection (0, 0) = 0.0 / 0.0 -- NaN

vectorDirection (x, y)

| x >= 0 && y >= 0 = a

| x < 0 && y >= 0 = pi - a

| x < 0 && y < 0 = pi + a

| otherwise = 2 * pi - a

where a = atan (abs y / abs x)

In other words, I used arctan (|y| / |x|) to get an angle, but since that angle's meaning changes depending on which quadrant the vector is in, I have to use case analysis to adjust it so that it becomes a nice standard angle between 0 and 2 * pi. This is the only way I saw it done in my old trigonometry book, but I was wondering if there was a more direct method.

Re: direction component of vector without case analysis

Angle =

works as a single formula for , except it's in the range

Re: direction component of vector without case analysis

Quote:

Originally Posted by

**johnsomeone** Angle =

works as a single formula for

, except it's in the range

Erm... well thanks, but [0, 2*pi) is most definitely the range I am looking for. Much more ideal for programming applications.

Re: direction component of vector without case analysis

You can use and to setup up your cases algebraically within a function. It's like building a switch statement into the formula, because it's an indicator function - it's 1 when is negative and 0 when is positive.

So far, you have what you seek, except that in the case, you'd like to add .

So we need to add only if the result is in the 4th quadrant, and so use to incorporate that. So do:

Thus, when and , have

Of course, you'll still need if-statements to check for x or y being 0.