code_junkie

Is it possible to write Quake's fast InvSqrt() function in C#?

Nov 12th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. float InvSqrt (float x)
  2. {
  3. float xhalf = 0.5f*x;
  4. int i = *(int*)&x;
  5. i = 0x5f3759df - (i>>1);
  6. x = *(float*)&i;
  7. x = x*(1.5f - xhalf*x*x);
  8. return x;
  9. }
  10.  
  11. Input: 79.67
  12. BitConverter Method: 00:00:01.2809018 (0.1120187)
  13. Union Method: 00:00:00.6838758 (0.1120187)
  14. Unsafe Method: 00:00:00.3376401 (0.1120187)
  15.  
  16. Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
  17. 1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
  18.  
  19. [StructLayout(LayoutKind.Explicit, Size=4)]
  20. private struct IntFloat {
  21. [FieldOffset(0)]
  22. public float floatValue;
  23.  
  24. [FieldOffset(0)]
  25. public int intValue;
  26.  
  27. // redundant assignment to avoid any complaints about uninitialized members
  28. IntFloat(int x) {
  29. floatValue = 0;
  30. intValue = x;
  31. }
  32.  
  33. IntFloat(float x) {
  34. intValue = 0;
  35. floatValue = x;
  36. }
  37.  
  38. public static explicit operator float (IntFloat x) {
  39. return x.floatValue;
  40. }
  41.  
  42. public static explicit operator int (IntFloat x) {
  43. return x.intValue;
  44. }
  45.  
  46. public static explicit operator IntFloat (int i) {
  47. return new IntFloat(i);
  48. }
  49. public static explicit operator IntFloat (float f) {
  50. return new IntFloat(f);
  51. }
  52. }
  53.  
  54. float InvSqrt(float x)
  55. {
  56. float xhalf = 0.5f * x;
  57. int i = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
  58. i = 0x5f3759df - (i >> 1);
  59. x = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
  60. x = x * (1.5f - xhalf * x * x);
  61. return x;
  62. }
  63.  
  64. unsafe float InvSqrt(float x) { ... }
Add Comment
Please, Sign In to add comment