#square-root #quake-3

q_rsqrt

An implementation of the fast inverse square root function from quake 3

2 releases

0.1.1 Jun 27, 2022
0.1.0 Jun 27, 2022

#1082 in Math

MIT/Apache

4KB

This is a implementation of the fast inverse square root function from quake 3.
It can be up to three times as fast as using the .sqrt() method on a float32
Keep in mind that fast inverse square root is only accurate within a one percent margin of error

Here's the original implementation:

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

	return y;
}

No runtime deps