Skip to content

Instantly share code, notes, and snippets.

@3ki5tj
Created November 18, 2014 22:52
Show Gist options
  • Select an option

  • Save 3ki5tj/151ede4da37a14fa9c0c to your computer and use it in GitHub Desktop.

Select an option

Save 3ki5tj/151ede4da37a14fa9c0c to your computer and use it in GitHub Desktop.
Inverse square root function
/*
* http://www.beyond3d.com/content/articles/8/
* http://www.beyond3d.com/content/articles/15/
*/
#include <stdio.h>
#include <math.h>
float inv_sqrt(float x)
{
float xh = 0.5f*x;
//unsigned i=*(unsigned *)&x;
int i = *(int *) & x;
i = 0x5f3759df - (i>>1);
x = *(float *) & i;
x = x*(1.5f - xh*x*x);
return x;
}
int main(void)
{
float x, xs1, xs_f;
double xs_d;
printf("Enter x: ");
scanf("%f", &x);
xs1 = inv_sqrt(x);
xs_d = 1.0/sqrt(x);
xs_f = (float)(xs_d);
printf("x = %.14f\n"
"inv_sqrt(x) = %.14f\n"
"c.f. = %.14f(float)\n"
" = %.14f(double)\n"
, x, xs1, xs_f, xs_d);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment