Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fast inverse square root algorithm #647

Merged
merged 5 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions math/binary/fast_inverse_sqrt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Calculating the inverse square root
// [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root)
package binary
yan-aint-nickname marked this conversation as resolved.
Show resolved Hide resolved

import (
"math"
)

// Assumes that number always positive
yan-aint-nickname marked this conversation as resolved.
Show resolved Hide resolved
// You don't want to deal with complex numbers
// "magic" number 0x5f3759df from base 16 to base 10 is equal to 1597463007
// math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f))
// and math.Float32frombits to *(*float32)(unsafe.Pointer(&b))
// 4 >> 1 = 2 bitwise shift to the right by one divides the number by 2
func FastInverseSqrt(number float32) float32 {
var i uint32
var y, x2 float32
const threehalfs float32 = 1.5

x2 = number * float32(0.5)
y = number
i = math.Float32bits(y) // evil floating point bit level hacking
i = 0x5f3759df - (i >> 1) // magic number and bitshift hacking
y = math.Float32frombits(i)

y = y * (threehalfs - (x2 * y * y)) // 1st iteration of Newton's method
y = y * (threehalfs - (x2 * y * y)) // 2nd iteration, this can be removed
return y
}
16 changes: 1 addition & 15 deletions math/binary/sqrt.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,4 @@

package binary

import (
"math"
)

const threeHalves = 1.5

func Sqrt(n float32) float32 {
var half, y float32
half = n * 0.5
z := math.Float32bits(n)
z = 0x5f3759df - (z >> 1) // floating point bit level hacking
y = math.Float32frombits(z)
y = y * (threeHalves - (half * y * y)) // Newton's approximation
return 1 / y
}
func Sqrt(n float32) float32 { return 1 / FastInverseSqrt(n) }
2 changes: 1 addition & 1 deletion math/binary/sqrt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"testing"
)

const epsilon = 0.2
const epsilon = 0.001

func TestSquareRootCalculation(t *testing.T) {
tests := []struct {
Expand Down