ZhangZhihui's Blog  

Note that there’s an infinite number of real values between math.SmallestNonzeroFloat64 (the float64 minimum) and math.MaxFloat64 (the float64 maximum). Conversely, the float64 type has a finite number of bits: 64. Because making infinite values fit into a finite space isn’t possible, we have to work with approximations. Hence, we may lose precision. The same logic goes for the float32 type.

 

Floating points in Go follow the IEEE-754 standard, with some bits representing a mantissa and other bits representing an exponent. A mantissa is a base value, whereas an exponent is a multiplier applied to the mantissa. In single-precision floating-point types (float32), 8 bits represent the exponent, and 23 bits represent the mantissa. In double-precision floating-point types (float64), the values are 11 and 52 bits, respectively, for the exponent and the mantissa. The remaining bit is for the sign. To convert a floating point into a decimal, we use the following calculation:

sign * 2^exponent * mantissa

 

Once we understand that float32 and float64 are approximations, what are the implications for us as developers? The first implication is related to comparisons. Using the == operator to compare two floating-point numbers can lead to inaccuracies. Instead, we should compare their difference to see if it is less than some small error value. For example, the testify testing library (https://github.com/stretchr/testify) has an InDelta function to assert that two values are within a given delta of each otherAlso bear in mind that the result of floating-point calculations depends on the actual processor. Most processors have a floating-point unit (FPU) to deal with such calculations. There is no guarantee that the result executed on one machine will be the same on another machine with a different FPU. Comparing two values using a delta can be a solution for implementing valid tests across different machines.

 

 

复制代码
func main() {
    var a float64
    fmt.Println(a)
    fmt.Println(1 / a)
    fmt.Println(-1 / a)
    fmt.Println(math.IsInf(1 / a, 1))
    fmt.Println(math.IsInf(-1 / a, 1))
    fmt.Println(math.IsInf(-1 / a, -1))
    fmt.Println(math.IsInf(-1 / a, 0))
    fmt.Println(math.IsInf(1 / a, 0))
}
复制代码

 

复制代码
zzh@ZZHPC:/zdata/Github/ztest$ go run main.go
0
+Inf
-Inf
true
false
true
true
true
复制代码

 

 

 

 

func main() {
    fmt.Printf("math.SmallestNonzeroFloat64:\n%.1080f\n\n", math.SmallestNonzeroFloat64)
    fmt.Printf("math.MaxFloat64:\n%.100f\n", math.MaxFloat64)
}

 

 

posted on   ZhangZhihuiAAA  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
 
点击右上角即可分享
微信分享提示