fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. // https://e...content-available-to-author-only...a.org/wiki/Fast_inverse_square_root
  5. float Q_rsqrt( float number )
  6. {
  7. long i;
  8. float x2, y;
  9. const float threehalfs = 1.5F;
  10.  
  11. x2 = number * 0.5F;
  12. y = number;
  13. i = * ( long * ) &y; // evil floating point bit level hacking
  14. i = 0x5f3759df - ( i >> 1 ); // what the fuck?
  15. y = * ( float * ) &i;
  16. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  17. //y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  18.  
  19. return y;
  20. }
  21.  
  22. void print(float n) {
  23. float result_1 = 1 / n;
  24.  
  25. float x = Q_rsqrt(n);
  26. float result_2 = x * x;
  27. printf("%f %f\n", result_1, result_2);
  28. }
  29.  
  30. int main() {
  31. print(1000.0f);
  32. print(100.0f);
  33. print(10.0f);
  34. print(1.0f);
  35. print(0.1f);
  36. print(0.01f);
  37. return 0;
  38. }
Success #stdin #stdout 0s 4516KB
stdin
Standard input is empty
stdout
0.001000 0.000997
0.010000 0.009969
0.100000 0.099658
1.000000 0.996617
10.000000 9.968114
100.000000 99.650749