Hi
I came across an article of how to find the value of 1/sqrt(x) quick.
the idea is to use the log bit wise and pointer operation ( floating point representation with the exponents and mantissas)
ie:
var y float64
var i int64
i= *(long *)&y //evil floating point bit hack
I do not quite understand this operation.
when I try to run it on goplay gound,
an error occur:
func main() {
var y = 2.15
var i int64
i=*(int64 *)&y // error syntax error: unexpected ), expecting expression
i= 0x5f3759df - (i>>1)
y= (float64)&i //error syntax error: unexpected ), expecting expression
fmt.Println(y)
}
could someone please enlighten me ?
Thanks
// Fast inverse square root
// https://en.wikipedia.org/wiki/Fast_inverse_square_root
package main
import (
"fmt"
"math"
)
func RSqrt(number float64) float64 {
const threehalfs = 1.5
x2 := number * 0.5
y := number
i := int64(math.Float64bits(y)) // evil floating point bit level hacking
i = 0x5FE6EB50C7B537A9 - (i >> 1) // what the f@#!?
y = math.Float64frombits(uint64(i))
y = y * (threehalfs - (x2 * y * y)) // 1st iteration
y = y * (threehalfs - (x2 * y * y)) // 2nd iteration
y = y * (threehalfs - (x2 * y * y)) // 3rd iteration
y = y * (threehalfs - (x2 * y * y)) // 4th iteration
return y
}
func main() {
number := 0.15625
fmt.Printf("%g\n", number)
rsqrt := RSqrt(number)
fmt.Printf("%g\n", rsqrt)
rsqrt = 1 / math.Sqrt(number)
fmt.Printf("%g\n", rsqrt)
}
Hi Petrus
Thank you very much for your help.
More importantly, I learn from you how to do the evil floating point bit level in golang.
once again Thank you very much!