dtjbcda841554 2016-06-10 23:06 采纳率: 0%
浏览 21
已采纳

Golang浮动64位

I'm trying to understand the Go Sqrt implementation and can't quite comprehend what is going on with the Float64bits function. I have some test code and output below. Why does the value of ix change so drastically with this operation?

package main

import ("math"
        "fmt")

func main()  {

    var x float64 = 4
    fmt.Printf("The value of x is: %v 
", x)

    ix := math.Float64bits(x)
    fmt.Printf("The value of ix is: %v 
", ix)
    fmt.Printf("The type of ix is: %T 
", ix)

}
The value of x is: 4 
The value of ix is: 4616189618054758400 
The type of ix is: uint64 
  • 写回答

3条回答 默认 最新

  • dongya3627 2016-06-10 23:31
    关注

    From the documentation, it converts the float64 into an uint64 without changing the bits, it's the way the bits are interpreted that change.

    Here is the full source code of the Float64bits function:

    func Float64bits(f float64) uint64 { return *(*uint64)(unsafe.Pointer(&f)) }
    

    Don't be scared by that syntax trick of using an unsafe Pointer, it's quite common in Go's source code (avoids copying the data). So, that really is that simple: take the binary data of the given float and interpret it as an unsigned integer.

    The reason it changes so much is because of the representation of floating point numbers. According to the specification, a floating point number is composed of a Sign, an Exponent and a Mantissa.

    On a 64 bits float, there is 1 bit for the Sign, 11 bits for the exponent and 52 bits for the mantissa.

    The representation of 4 as a 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 that this value is 4616189618054758400 if interpreted as an unsigned integer. You'll find plenty of great tutorials on the web regarding the IEEE754 to understand fully how the above value is a representation of 4.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路