-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add fast inverse square root algorithm (#647)
* Add fast inverse square root algorithm * PR improvements see comments in #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]>
- Loading branch information
1 parent
6429dfd
commit f7ca03b
Showing
3 changed files
with
31 additions
and
16 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
import ( | ||
"math" | ||
) | ||
|
||
// FastInverseSqrt assumes that argument is always positive, | ||
// and it does not deal with negative numbers. | ||
// The "magic" number 0x5f3759df is hex for 1597463007 in decimals. | ||
// The math.Float32bits is alias to *(*uint32)(unsafe.Pointer(&f)) | ||
// and math.Float32frombits is to *(*float32)(unsafe.Pointer(&b)). | ||
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters