by Richard Russell, September 2007
BBC BASIC includes the ATN (arctangent) function as standard, but it does not include the ATAN2 function available in some other programming languages. The difference between them is that ATN takes a single parameter and returns its arctangent in the range -PI/2 to +PI/2, whereas ATAN2 takes two parameters and returns the arctangent of their quotient in the range -PI to +PI. In other words ATAN2 is able to work out the correct quadrant for the result.
For more details on the significance and uses of the ATAN2 function see the relevant Wikipedia article.
ATAN2 can be implemented in BBC BASIC using the following code:
DEF FNatan2(y,x) : ON ERROR LOCAL = SGN(y)*PI/2 IF x>0 THEN = ATN(y/x) ELSE IF y>0 THEN = ATN(y/x)+PI ELSE = ATN(y/x)-PI
Note that the possibility of a Division by zero error (if x=0) or a Number too big error (if y is very much larger than x) is handled by local error trapping. This is an example of when it is more straightforward to allow the error to occur, and trap it, rather than predict when the error will occur and avoid it. This is because the precise values of x and y which might cause a Number too big error are difficult to determine, and depend on the *FLOAT mode in use.
For this reason take particular care to transcribe the code accurately, since any error you may introduce will be trapped and result in an incorrect return value rather than an error message.