File tree 3 files changed +31
-16
lines changed
3 files changed +31
-16
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change 7
7
8
8
package binary
9
9
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 ) }
Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ import (
10
10
"testing"
11
11
)
12
12
13
- const epsilon = 0.2
13
+ const epsilon = 0.001
14
14
15
15
func TestSquareRootCalculation (t * testing.T ) {
16
16
tests := []struct {
You can’t perform that action at this time.
0 commit comments