2025-02-13 13:33:35 -08:00

46 lines
1.6 KiB
Typst

#import "@local/handout:0.1.0": *
= Introduction
In 2005, ID Software published the source code of _Quake III Arena_, a popular game released in 1999. \
This caused quite a stir: ID Software was responsible for many games popular among old-school engineers (most notably _Doom_, which has a place in programmer humor even today).
#v(2mm)
Naturally, this community immediately began dissecting _Quake_'s source. \
One particularly interesting function is reproduced below, with original comments: \
#v(3mm)
```c
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 ); // [redacted]
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;
}
```
#v(3mm)
This code defines a function `Q_sqrt`, which was used as a fast approximation of the inverse square root in graphics routines. (in other words, `Q_sqrt` efficiently approximates $1 div sqrt(x)$)
#v(3mm)
The key word here is "fast": _Quake_ ran on very limited hardware, and traditional approximation techniques (like Taylor series)#footnote[Taylor series aren't used today, and for the same reason. There are better ways.] were too computationally expensive to be viable.
#v(3mm)
Our goal today is to understand how `Q_sqrt` works. \
To do that, we'll first need to understand how computers represent numbers. \
We'll start with simple binary integers---turn the page.