平方根倒数速算法


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAGIC_NUMBER 0x5F3759DF

/* 平方根倒数速算法 */
static float inv_sqrt(float x) {
    float x_half = 0.5f * x;
    //long i = *(long *)&x;   /* get bits for floating value */

    //i = 0x5F3759DF - (i >> 1);  /* gives initial guess y0 */
    //x = *(float *)&i;   /* convert bits back to float */
    *(long *)&x = MAGIC_NUMBER - (*(long *)&x >> 1);  /* gives initial guess y0 */
    x = x * (1.5f - x_half * x * x);    /* Newton step, repeating increases accuracy */

    return x;
}

int main(void) {
    float flt = 3.14f;

    printf("%f\n", 1.0f / (float)sqrt(flt));
    printf("%f\n", inv_sqrt(flt));

    return 0;
}



你可能感兴趣的:(平方根倒数速算法)