Home > linux, nerdcore, software > source code comments update

source code comments update

One of the posts in yesterdays article (source-code-comments) was about a function used in the Quake3 sources. I fiddled around with it to understand what it does and am amazed of the compute power of this little snippet:

#define _GNU_SOURCE
#include <assert .h>
#include <stdio .h>
#include <stdlib .h>
#include <math .h>
 
float Q_rsqrt( float number )
{
  long i;
  float x2, y;
  const float threehalfs = 1.5F;
 
  x2 = number * 0.5F;
  y  = number;
  i  = * ( long * ) &y;  /* evil floating point bit level hacking */
  i  = 0x5f3759df - ( i >> 1 ); /* what the fuck? */
  y  = * ( float * ) &i;
  y  = y * ( threehalfs - ( x2 * y * y ) ); /* 1st iteration */
  /* y  = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed */
 
  #ifndef Q3_VM
  #ifdef __linux__
    assert( !isnan(y) ); /* bk010122 - FPE? */
  #endif
  #endif
  return y;
}
 
int 
main (int argc, char *argv[])
{
    char * line = NULL;
    size_t len = 0;
    float input=42.23;
 
    printf("type in a float e.g: 42.23\nvalue: ");
    getline(&line, &len, stdin);
    input = strtof(line, (char **) NULL);
    printf ("reverse square root of %.6f is %.6f \n", input, Q_rsqrt(input));
 
    if (line) free(line);
 
    return 0;
}</math></stdlib></stdio></assert>
 gcc -ansi -pedantic -Wall -D_XOPEN_SOURCE=600 Q3_inv_sqrt.c -o Q3rsqrt

Categories: linux, nerdcore, software Tags: ,
  1. ronny
    April 26th, 2009 at 18:57 | #1

    John Carmack … die Funktion ist wirklich toll.

  1. No trackbacks yet.