вторник, 27 июля 2010 г.

Алгоритм приближённого вычисления квадратного корня


#ifndef __fast_inv_sqrt_h__
#define __fast_inv_sqrt_h__

#include <cassert>
#include <stdint.h>


/**
* Fast approximation of the inverse square root
* (http://en.wikipedia.org/wiki/Fast_inverse_square_root)
*
* @param x
* 32-bit floating point (IEEE 754-2008)
* @return the approximated inverse square root of x
*/
inline float InvSqrt(float x) {
assert( sizeof(x) == 4 );
assert( x >= 0 );

union {
uint32_t i;
float y;
};

y = x;
i = 0x5f375a86 - (i >> 1);
/* Approximation step */

return y * (1.5f - 0.5f * x * y * y);
/* One step more of the Newton's method */
}

#endif /*_fast_inv_sqrt_h__*/

Комментариев нет: