CodingTrain / CodingTrain/Suggestion-Box

More Bit-Shifting Examples: The Fast 1/sqrt()

Open
#1,110 9 comments 2 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
570
Forks
85
PR merge metrics
No merged PRs in 30d

Description

Back in the late 90s, the game Quake III was very influential in the computer graphics sector by taking huge advantage of bit-shifting in order to estimate the value of y=1/√x many times per frame for lighting calculations and to normalise vectors.

The original code was written in C meaning it makes heavy use of pointers so off the top of my head I don't know if an equivalent algorithm can be implemented in Java/Javascript. However if so, it would be a good way to demonstrate the power of bit-shifting beyond the 8 segment display and simple halving.

Because the code was requested in the comments (copied from [here](https://en.wikipedia.org/wiki/Fast_inverse_square_root) and re-commented):

```
float Q_rsqrt( float number )
{
//personally not too fond of all these variable declarations (like "threehalfs")
//but that's how it is usually presented so I just went with it
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;

//Below is the magic part, not sure what is happening but it seems to be converting y to long
i = * ( long * ) &y;

//Bitshifting the exponent to divide it by 2 (hence applying sqrt). This is what makes it fast
i = 0x5f3759df - ( i >> 1 );

//Turning the value back to float
y = * ( float * ) &i;

//1st iteration of Newton-Raphson Method
y = y * ( threehalfs - ( x2 * y * y ) );

//2nd iteration, this is optional unless great precision is required
//alternatively more can be added if more precision is needed
y = y * ( threehalfs - ( x2 * y * y ) );
return y;
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.