[C language] alien language job

In 3D graphics programming, it is often required or reciprocal square root, for example: find the length of a vector or vector normalization. C Math Library in sqrt have the desired accuracy, but for 3D games program is too slow. We hope to be able to ensure sufficient accuracy at the same time, further increase speed.

Carmack in using the following algorithm QUAKE3, which for the first time when the public appears almost overawed by all the people. It is said that the algorithm is not really Carmack invention, its true author is Nvidia's Gary Tarolli (unconfirmed).

This algorithm allows to calculate the inverse square root calculation speed increased by four times, led the revolutionary 3D game. Without this algorithm, I am afraid that now 3D game where the object is still no shadow (think of CS images).

This algorithm appeared in the last century, but the only concern 10 years ago, circle games, algorithm principle is clear, but as the core of the algorithm that constant 0x5f3759df, since no one knows how it was out. There are rumors that this constant is left when an alien invasion internet.

//

// calculate parameters reciprocal square root of x

//

float InvSqrt (float x)

{

float xhalf = 0.5f*x;

int i = *(int*)&x;

i = 0x5f3759df - (i >> 1); 

x = *(float*)&i;

x = x*(1.5f - xhalf*x*x); 

return x;

}

If you require a floating-point reciprocal square root of x, what with the C library of mathematical functions sqrt function and use more than the absolute value of the error function InvSqrt obtained results it is how much?

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float InvSqrt (float x)
{
 float xhalf = 0.5f*x;
 int i = *(int*)&x;
 i = 0x5f3759df - (i >> 1); 
 x = *(float*)&i;
 x = x*(1.5f - xhalf*x*x); 
 return x;
}
int main()
{
 int n;
 float x;
 scanf("%d",&n);
 for(int i =0;i<n;i++)
 {   
  scanf("%f",&x);
  printf("%f\n",fabs(1.0/sqrt(x)-InvSqrt(x)));
 }
 return 0;
}

Guess you like

Origin www.cnblogs.com/asher0608/p/11689461.html