跳过正文

浮点数

·318 字
目录

IEEE-754 浮点数标准
#

Go 使用 IEEE-754 标准,使用以 2 为底的指数表示小数,如 0.085 可以用指数的形式表示为 1.36*2^-4

单精度与双精度浮点数格式
#

精度符号位指数位小数位偏移量
单精度(32Bits)1Bit(31)8Bits(30-23)23Bits(22-0)127
双精度(64Bits)1Bit(63)11Bits(62-52)52Bits(51-0)1023

Go float32精度为6位小数,float64精度为15位

判断浮点数是否为整数
#

package main

import (
    "fmt"
    "math"
)

func main() {
    f := float64(1.1)
    IsInt(f)
}

// 判断浮点数是否是整数
// 依据就是指数是否大于等于小数位数
// 即1.2*10^2为整数,1.222*10^2为浮点数
func IsInt(f float64) bool {
    bits := math.Float64bits(math.Abs(f))
    bias := 1023

    exponent := int(bits>>52) - bias - 52               //指数?
    coefficient := (bits & ((1 << 52) - 1)) | (1 << 52) // 系数 = 1 + 小数
    intTest := (coefficient & (1<<uint32(-exponent) - 1))
    fmt.Printf("\nExponent: %d Coefficient: %d IntTest: %d\n", exponent, coefficient, intTest)
    if exponent < -52 || (exponent < 0 && intTest != 0){
        fmt.Printf("Not Integer\n")
        return false
    }

    fmt.Println("Integer")
    return true
}

IsInt()代码改自《Go 语言底层原理剖析》-郑建勋