Advertisement
marcopennekamp

Fast Arctan2

Nov 11th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. /*
  2.  
  3. Written by Marco Pennekamp.
  4.  
  5.  
  6. arctan2 results:
  7.  
  8. 1e6 iterations.
  9.  
  10. Fast arctan2:
  11. 14763917 ns
  12. 13036519 ns
  13. 13084908 ns
  14. 12826451 ns
  15. 12405162 ns
  16. 12806097 ns
  17. 12592956 ns
  18. 12683205 ns
  19. 12366759 ns
  20. 12316065 ns
  21.  
  22. Math atan2:
  23. 127117003 ns
  24. 124614619 ns
  25. 122801197 ns
  26. 126679586 ns
  27. 123187922 ns
  28. 124409927 ns
  29. 122724773 ns
  30. 121995871 ns
  31. 122014689 ns
  32. 122691362 ns
  33.  
  34. So, about 10x faster and 12 - 14ns per arctan2 call.
  35.  
  36.  
  37. Accuracy: (randomly taken values)
  38.  
  39.         Fast            Java
  40.  
  41. x<0;y>0     -1.215991       -1.2179305185113805
  42. x<0;y<0     -2.1207047      -2.1160234823321717
  43. x>0;y>0     1.5273854       1.5273896081693032
  44. x>0;y<0     2.3276424       2.3288875696242464
  45.  
  46. Conclusion: Not a very good accuracy, but enough for most games, especially when the yaw is calculated each update.
  47. */
  48.  
  49.    
  50. public static float arctan (float x) {
  51.     if (x > 1) {
  52.         return 1.57079632675f - x / (x * x + 0.28f);
  53.     }else if (x < -1) {
  54.         return -1.57079632675f - x / (x * x + 0.28f);
  55.     }else {
  56.         return x / (1f + 0.28f * x * x);
  57.     }
  58. }
  59.    
  60. public static float arctan2 (float y, float x) {
  61.     if (x > 0) {
  62.         return arctan (y / x);
  63.     }else if (x < 0) {
  64.         if (y >= 0) {
  65.             return arctan(y / x) + 3.1415926535f;
  66.         }
  67.         return arctan(y / x) - 3.1415926535f;
  68.     }
  69.            
  70.     if (y > 0) {
  71.         return 1.57079632675f;
  72.     }
  73.     if (y < 0) {
  74.         return -1.57079632675f;
  75.     }
  76.        
  77.     return 0;
  78. }
  79.  
  80.  
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement