FastInverseSqrt assumes that argument is always positive, and it does not deal with negative numbers. The "magic" number 0x5f3759df is hex for 1597463007 in decimals. The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f)) and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)).
(number float32)
| 15 | // The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f)) |
| 16 | // and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)). |
| 17 | func FastInverseSqrt(number float32) float32 { |
| 18 | var i uint32 |
| 19 | var y, x2 float32 |
| 20 | const threehalfs float32 = 1.5 |
| 21 | |
| 22 | x2 = number * float32(0.5) |
| 23 | y = number |
| 24 | i = math.Float32bits(y) // evil floating point bit level hacking |
| 25 | i = 0x5f3759df - (i >> 1) // magic number and bitshift hacking |
| 26 | y = math.Float32frombits(i) |
| 27 | |
| 28 | y = y * (threehalfs - (x2 * y * y)) // 1st iteration of Newton's method |
| 29 | y = y * (threehalfs - (x2 * y * y)) // 2nd iteration, this can be removed |
| 30 | return y |
| 31 | } |