퀘이크 III의 고속 역제곱근(Fast Inverse Square Root) 알고리즘과 원리Quake III's Fast Inverse Square Root Algorithm and Mathematical Principles
3D 벡터 정규화(1/sqrt(x))를 위해 IEEE 754 부동소수점 비트 재해석(0x5f3759df)과 뉴턴-랩슨(Newton-Raphson) 근사법을 결합한 수치 연산 기법 해설입니다.An analysis of the numerical approximation technique combining IEEE 754 floating-point bit reinterpretation (0x5f3759df) and Newton-Raphson iteration to compute 1/sqrt(x) for 3D vector normalization.
0x5f3759df - (i >> 1)), 뉴턴-랩슨(Newton-Raphson) 1회 반복으로 오차를 약 0.175% 이내로 줄인 수치 근사 알고리즘입니다.0x5f3759df - (i >> 1)) and refined it with a single Newton-Raphson step to within ~0.175% maximum relative error.1. 고속 역제곱근 원본 C 코드 및 안전한 현대식 변환1. Original Fast Inverse Square Root C Code and Standards-Compliant Variant
#include <stdint.h>
#include <string.h>
// 1. Quake III Arena 원본 스타일 (역사적 참고용)
float Q_rsqrt_legacy(float number)
{
int32_t i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = *(int32_t *)&y; // 부동소수점 비트를 정수로 재해석 (Strict Aliasing 위반 가능)
i = 0x5f3759df - (i >> 1); // 지수부 반감 및 가수부 보정 상수 적용
y = *(float *)&i; // 다시 부동소수점으로 재해석
y = y * (threehalfs - (x2 * y * y)); // 뉴턴-랩슨(Newton-Raphson) 1차 근사
return y;
}
// 2. C99/C11 표준 준수 버전 (memcpy를 통한 Strict Aliasing 회피)
float Q_rsqrt_safe(float number)
{
uint32_t i;
float x2 = number * 0.5f;
float y = number;
memcpy(&i, &y, sizeof(float));
i = 0x5f3759dfu - (i >> 1);
memcpy(&y, &i, sizeof(float));
return y * (1.5f - (x2 * y * y));
}
#include <stdint.h>
#include <string.h>
// 1. Original Quake III Arena style (for historical reference)
float Q_rsqrt_legacy(float number)
{
int32_t i;
float x2, y;
const float threehalfs = 1.5F;
x2 = number * 0.5F;
y = number;
i = *(int32_t *)&y; // Reinterpret float bits as integer (violates Strict Aliasing)
i = 0x5f3759df - (i >> 1); // Halve exponent and apply mantissa bias constant
y = *(float *)&i; // Reinterpret integer bits back as float
y = y * (threehalfs - (x2 * y * y)); // 1st Newton-Raphson refinement iteration
return y;
}
// 2. C99/C11 standards-compliant version (avoids Strict Aliasing UB via memcpy)
float Q_rsqrt_safe(float number)
{
uint32_t i;
float x2 = number * 0.5f;
float y = number;
memcpy(&i, &y, sizeof(float));
i = 0x5f3759dfu - (i >> 1);
memcpy(&y, &i, sizeof(float));
return y * (1.5f - (x2 * y * y));
}
2. 실무 적용 및 주의사항2. Practical Considerations and Caveats
- 현대 CPU에서는 하드웨어 SIMD 명령어(
rsqrtss)가 더 빠름: 최신 x86(SSErsqrtss), ARM(NEONvrsqrte), GPU 셰이더 유닛은 전용 역제곱근 하드웨어 회로를 내장하고 있습니다. 현대 프로세서에서Q_rsqrt를 직접 쓰면 부동소수점 레지스터(XMM)와 정수 레지스터(GPR) 간 데이터 이동 지연이 오히려 더 크므로, 표준1.0f / sqrtf(x)또는 SIMD 내장 함수를 사용해야 합니다. - C/C++ 엄격한 별칭 규칙(Strict Aliasing Rule) 주의: 원본 코드의
*(long *)&y포인터 타입 캐스팅은 현대 GCC/Clang의-O2이상 최적화에서 정의되지 않은 동작(Undefined Behavior)으로 분류되어 잘못된 기계어를 생성할 수 있습니다. 비트 재해석이 필요할 때는memcpy나 C++20std::bit_cast를 사용해야 합니다. - 64비트 환경에서의 자료형 크기: 원본의
long타입은 64비트 Linux(LP64) 환경에서 8바이트이므로 4바이트float와 크기가 맞지 않습니다. 반드시 고정 폭 정수형인int32_t또는uint32_t를 명시해야 합니다.
- Modern CPUs Have Faster Dedicated Hardware Instructions (
rsqrtss): Contemporary x86 (SSErsqrtss), ARM (NEONvrsqrte), and GPU shader cores include dedicated hardware reciprocal square root units. Moving values between floating-point (XMM) and general-purpose integer registers in software is slower on modern hardware than calling1.0f / sqrtf(x)or SIMD intrinsics. - Avoid C/C++ Strict Aliasing Undefined Behavior: Dereferencing a type-punned pointer (
*(long *)&y) violates the C99/C++ Strict Aliasing Rule and can break under-O2/-O3compiler optimizations. Always usememcpy(which compiles down to a single register move) or C++20std::bit_cast. - Use Fixed-Width 32-Bit Integers (
uint32_t): Becauselongis 64 bits (8 bytes) on 64-bit Linux/macOS (LP64), always useint32_toruint32_tto match the 32-bit width of IEEE 754float.
고속 역제곱근 알고리즘은 오늘날 직접 호출할 일은 드물지만, IEEE 754 부동소수점의 지수·가수 비트 배열을 이진 로그($\log_2$)의 선형 근사로 해석하고 뉴턴-랩슨 해법과 결합한 컴퓨터 공학의 대표적인 수치 최적화 사례로 의미가 있습니다.
While hardware SIMD instructions have superseded Q_rsqrt in production code, the algorithm remains an instructive case study in exploiting IEEE 754 binary layout as a piecewise linear approximation of $\log_2(x)$ paired with Newton-Raphson root finding.