Skip to content

Commit f7ca03b

Browse files
Add fast inverse square root algorithm (TheAlgorithms#647)
* Add fast inverse square root algorithm * PR improvements see comments in TheAlgorithms#647 * Update math/binary/fast_inverse_sqrt.go file docstring Co-authored-by: Taj <[email protected]> * Update math/binary/fast_inverse_sqrt.go function documentation Co-authored-by: Taj <[email protected]> * Fix function documentation grammar Co-authored-by: Taj <[email protected]> --------- Co-authored-by: Taj <[email protected]>
1 parent 6429dfd commit f7ca03b

File tree

3 files changed

+31
-16
lines changed

3 files changed

+31
-16
lines changed

Diff for: math/binary/fast_inverse_sqrt.go

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Calculating the inverse square root
2+
// [See more](https://en.wikipedia.org/wiki/Fast_inverse_square_root)
3+
4+
package binary
5+
6+
import (
7+
"math"
8+
)
9+
10+
// FastInverseSqrt assumes that argument is always positive,
11+
// and it does not deal with negative numbers.
12+
// The "magic" number 0x5f3759df is hex for 1597463007 in decimals.
13+
// The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f))
14+
// and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)).
15+
func FastInverseSqrt(number float32) float32 {
16+
var i uint32
17+
var y, x2 float32
18+
const threehalfs float32 = 1.5
19+
20+
x2 = number * float32(0.5)
21+
y = number
22+
i = math.Float32bits(y) // evil floating point bit level hacking
23+
i = 0x5f3759df - (i >> 1) // magic number and bitshift hacking
24+
y = math.Float32frombits(i)
25+
26+
y = y * (threehalfs - (x2 * y * y)) // 1st iteration of Newton's method
27+
y = y * (threehalfs - (x2 * y * y)) // 2nd iteration, this can be removed
28+
return y
29+
}

Diff for: math/binary/sqrt.go

+1-15
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,4 @@
77

88
package binary
99

10-
import (
11-
"math"
12-
)
13-
14-
const threeHalves = 1.5
15-
16-
func Sqrt(n float32) float32 {
17-
var half, y float32
18-
half = n * 0.5
19-
z := math.Float32bits(n)
20-
z = 0x5f3759df - (z >> 1) // floating point bit level hacking
21-
y = math.Float32frombits(z)
22-
y = y * (threeHalves - (half * y * y)) // Newton's approximation
23-
return 1 / y
24-
}
10+
func Sqrt(n float32) float32 { return 1 / FastInverseSqrt(n) }

Diff for: math/binary/sqrt_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"testing"
1111
)
1212

13-
const epsilon = 0.2
13+
const epsilon = 0.001
1414

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

0 commit comments

Comments
 (0)