go - Golang Float64bits -


i'm trying understand go sqrt implementation , can't quite comprehend going on float64bits function. have test code , output below. why value of ix change drastically operation?

package main  import ("math"         "fmt")  func main()  {      var x float64 = 4     fmt.printf("the value of x is: %v \n", x)      ix := math.float64bits(x)     fmt.printf("the value of ix is: %v \n", ix)     fmt.printf("the type of ix is: %t \n", ix)  } value of x is: 4  value of ix is: 4616189618054758400  type of ix is: uint64  

from documentation, converts float64 uint64 without changing bits, it's way bits interpreted change.

here full source code of float64bits function:

func float64bits(f float64) uint64 { return *(*uint64)(unsafe.pointer(&f)) } 

don't scared syntax trick of using unsafe pointer, it's quite common in go's source code (avoids copying data). so, simple: take binary data of given float , interpret unsigned integer.

the reason changes because of representation of floating point numbers. according specification, floating point number composed of sign, exponent , mantissa.

on 64 bits float, there 1 bit sign, 11 bits exponent , 52 bits mantissa.

the representation of 4 floating point number on 64 bits is:

0b0100 0000 0001 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000   seee eeee eeee mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm mmmm 

it turns out value 4616189618054758400 if interpreted unsigned integer. you'll find plenty of great tutorials on web regarding ieee754 understand how above value representation of 4.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -