coddding - 6 months ago 42

C++ Question

How would i go about taking my

`atan`

`atan2`

For example

`float myAtan2(double a, double b)`

{

float atan2val = //calculate atan2 using atan

return atan2val;

}

Sorry I'm not the best at trigonometry!

Answer

Something like this:

```
float myAtan2(double a, double b)
{
float atan2val;
if (b > 0) {
atan2val = atan(a/b);
}
else if ((b < 0) && (a >= 0) {
atan2val = atan(a/b) + pi;
}
else if ((b < 0) && (a < 0) {
atan2val = atan(a/b) - pi;
}
else if ((b = 0) && (a > 0)) {
atan2val = pi / 2;
}
else if ((b = 0) && (a < 0)) {
atan2val = 0 - (p / 2 );
}
else if ((b = 0) && (a = 0)) {
atan2val = 1000; //represents undefined
}
return atan2val;
}
```

You can probably code it prettier, but that's the logic, which I got from here: https://en.wikipedia.org/wiki/Atan2#Definition_and_computation.

I'm returning 1000 (an impossible value for an arctan) to represent "undefined". You could do it some other way maybe by using NaN or something.

Source (Stackoverflow)