Skip to content

Instantly share code, notes, and snippets.

@shawnsmithdev
Created January 1, 2021 00:46

Revisions

  1. shawnsmithdev created this gist Jan 1, 2021.
    23 changes: 23 additions & 0 deletions qrsqrt.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    // This is the Quake III Q_rsqrt Fast Approx Inverse Square Root algorithm

    package main

    import (
    "fmt"
    "math"
    )

    const threehalfs float32 = 1.5

    func qrsqrt(number float32) float32 {
    i := math.Float32bits(number)
    i = 0x5f3759df - (i >> 1)
    y := math.Float32frombits(i)

    x2 := number * 0.5
    return y * (threehalfs - (x2 * y * y))
    }

    func main() {
    fmt.Println(qrsqrt(27)) // prints 0.19215362 for 0.154% error
    }