home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / delphi.swg / 0046_Duplicate C function ATAN2 in Delphi.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1995-11-24  |  1.3 KB  |  43 lines

  1.  
  2. {I think the following will work, If not the net gods will comment.}
  3.  
  4. function sgn (a : real) : real;
  5. begin
  6.   if a < 0  then  sgn := -1;
  7.             else  sgn :=  1;
  8. end;
  9.  
  10. function atan2 (y, x : real) : real;
  11. begin
  12.   if x > 0       then  atan2 := arctan (y/x)
  13.   else if x < 0  then  atan2 := arctan (y/x) + pi
  14.   else                 atan2 := pi/2 * sgn (y);
  15. end;
  16.  
  17. I think you should seriously consider using the FPATAN instruction for this!
  18.  
  19. This x87 opcode implements an IEEE-compliant ATAN2() function, with full extended
  20. precision, and the hardware will handle all the special cases for you.
  21.  
  22. If you have numeric exceptions enabled, and input bogus values, the x87 chip will 
  23. raise the appropriate signal, without the need for upfront testing of parameters.
  24.  
  25. A BP/TP/Delphi-compatible version would look like this:
  26.  
  27. Function atan2(y : extended; x : extended): Extended;
  28. Assembler;
  29. asm
  30.   fld [y]
  31.   fld [x]
  32.   fpatan
  33. end;
  34.  
  35. Total execution time is less than 200 cycles on a Pentium, with less than 1 ulp 
  36. maximum error, unless you have a Pentium with the FDIV bug, where it could fail
  37. almost anywhere after the first 15-20 OK bits!  :-)
  38.  
  39. The library function ArcTan(x) is implemented as fpatan(1.0,x), as long as you
  40. compile with IEEE reals {$N+} set.
  41.  
  42. Terje
  43.