Skip to content

Instantly share code, notes, and snippets.

@SimZhou
Last active February 13, 2022 14:15
Show Gist options
  • Save SimZhou/4a0304f2a16e70fa7a9fa7842b7edf7c to your computer and use it in GitHub Desktop.
Save SimZhou/4a0304f2a16e70fa7a9fa7842b7edf7c to your computer and use it in GitHub Desktop.
Fast inverse square root in Golang
// The Fast Inverse Square Root code in the game "Quake"
// translated from C
// Reference: https://en.wikipedia.org/wiki/Fast_inverse_square_root
package main
import (
"fmt"
"unsafe"
)
func Q_rsqrt(number float32) float32 {
var i int32
var x2, y float32
const threehalfs float32 = 1.5
x2 = number * 0.5
y = number
i = *(*int32)(unsafe.Pointer(&y))
i = 0x5F3759DF - (i >> 1)
y = *(*float32)(unsafe.Pointer(&i))
y = y * (threehalfs - (x2 * y * y))
// y = y * (theehalfs - (x2 * y * y))
return y
}
func main() {
x := Q_rsqrt(2)
fmt.Printf("%.10f", 1/x)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment