v / vlib / math / q_rsqrt.v
18 lines · 17 sloc · 608 bytes · 03e0b9e646c75e787c6e3c12b45cbc55278b9732
Raw
1module math
2
3// q_sqrt computes an approximation of the inverse square root (1 / √x) using a fast
4// inverse square root algorithm. This method is often used in applications
5// where performance is crucial, such as in computer graphics or physics
6// simulations.
7// (This algorithm is inspired by the famous "fast inverse square root" code
8// used in the Quake III Arena game engine.)
9@[inline]
10pub fn q_rsqrt(x f64) f64 {
11 x_half := 0.5 * x
12 mut i := i64(f64_bits(x))
13 i = 0x5fe6eb50c7b537a9 - (i >> 1)
14 mut j := f64_from_bits(u64(i))
15 j *= (1.5 - x_half * j * j)
16 j *= (1.5 - x_half * j * j)
17 return j
18}
19