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 2024-02-14 21:31  ZhangZhihuiAAA  阅读(17)  评论(0)    收藏  举报