Skip to content

Instantly share code, notes, and snippets.

@yan-aint-nickname
Created August 24, 2023 09:03
Show Gist options
  • Save yan-aint-nickname/7be20c6903e4d434a3d04d788b5fcdb1 to your computer and use it in GitHub Desktop.
Save yan-aint-nickname/7be20c6903e4d434a3d04d788b5fcdb1 to your computer and use it in GitHub Desktop.
Fast inverse square root
package main
import (
"unsafe"
)
// Assumes that number always positive
// You don't want to deal with complex numbers
func Q_rsqrt(number float32) float32 {
var i int32
var y float32
const threehalfs float32 = 1.5
var x2 float32 = number * float32(0.5)
y = number
i = *(*int32)(unsafe.Pointer(&y)) // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1) // what the fuck?
y = *(*float32)(unsafe.Pointer(&i))
y = y * (threehalfs - (x2 * y * y)) // 1st iteration
y = y * (threehalfs - (x2 * y * y)) // 2nd iteration, this can be removed
return y
}
package main
import (
"math"
"testing"
)
var EPSILON float32 = 0.0001
func floatEquals(a, b float32) bool {
if (a-b) < EPSILON && (b-a) < EPSILON {
return true
}
return false
}
func Test_Q_rsqrt(t *testing.T) {
result16 := float32(16) * Q_rsqrt(16)
resultFromMath16 := float32(math.Sqrt(16))
if !floatEquals(result16, resultFromMath16) {
t.Errorf("Floating numbers %f and %f doesn't match", result16, resultFromMath16)
}
result4 := float32(4) * Q_rsqrt(4)
resultFromMath4 := float32(math.Sqrt(4))
if !floatEquals(result4, resultFromMath4) {
t.Errorf("Floating numbers %f and %f doesn't match", result4, resultFromMath4)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment