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 other. Also 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) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律