The identity is only correct if a>0. If a<0 then it becomes . Similarly, if it does not necessarily follow that . In your case, the condition for this to hold is . If then again you have to add to the angle, to get the vector pointing the right way.

I think that the quickest way to ensure that your formula works in all four quadrants is to define , where the angled brackets denote a Boolean expression taking the value 1 if and 0 otherwise. Then define .

I think that should work in each quadrant, but it could still go wrong in the exceptional cases where or .