How to write an ATan2( ) function?

Blitz3D Forums/Blitz3D Programming/How to write an ATan2( ) function?

JoshK(Posted 2003) [#1]
I am compiling a 3D vector and quarternion lib in PB, which has an ATan() but no ATan2() function. Can anyone tell me how to write an ATan2() function?


JoshK(Posted 2003) [#2]
Got it. I didn't realize it was such a simple thing.

Procedure.f ATan2(y.f,x.f)
a.f=ATan(y.f/x.f)
If x.f<0.0
a.f=180.0+a.f
EndIf
If a.f>180.0
a.f=a.f-360.0
EndIf
ProcedureReturn a.f
Endprocedure


soja(Posted 2003) [#3]
I think it would be something along these lines:

ATan2() would take two parameters (y#, x#) and return the arctangent of y/x. The way I understand it, it's a "quadrant-specific" version of arctangent...

If x = 0 And y = 0 Then Return FAIL
If x = 0 And y > 0 Then Return 90
If x = 0 And y < 0 Then Return -90
If x > 0 And y = 0 Then Return 0
If x > 0 And y <> 0 Then Return ATan(y/x)
If x < 0 And y = 0 Then Return 180
If x < 0 And y <> 0 Then Return (180 - ATan(Abs(y) / Abs(x))) * Sgn(Y)

Test that out (and optimize it) before you use it.

<EDIT> Whoops, that's what I get for waiting to reply...


marksibly(Posted 2003) [#4]
Hi,

That's not quite right Halo.

What you need to do is look at the sign of the 2 arguments to work out which 'quadrant' the 2d vector is pointing into.

You then adjust the result of Atan correspondingly.

The problem with plain Atan is that it only has one 'sign' to go on.


sswift(Posted 2003) [#5]
Procedure.f ATan2(y.f,x.f)
a.f=ATan(y.f/x.f)


That code will give you a divide by 0 error if X is 0.