以下摘自The Go Programming Language:
A float32 provides approximately six decimal digits of precision, whereas a float64 provides about 15 digits; float64 should be preferred for most purposes because float32 computations accumulate error rapidly unless one is quite careful, and the smallest positive integer that cannot be exactly represented as a float32 is not large:
var f float32 = 16777216 // 1 << 24
fmt.Println(f == f+1) // “true”!
因为float32
计算时累计错误很快,所以大多数时候推荐使用float64
。
The math package has functions for creating and detecting the special values defined by IEEE 754: the positive and negative infinities, which represent numbers of excessive magnitude and the result of division by zero; and NaN (“not a number”), the result of such mathematically dubious operations as 0/0 or Sqrt(-1).
var z float64
fmt.Println(z, -z, 1/z, -1/z, z/z) // “0 -0 +Inf -Inf NaN”
要注意正负0
,正负无穷和NaN
。
The function math.IsNaN tests whether its argument is a not-a-number value, and math.NaN returns such a value. It’s tempting to use NaN as a sentinel value in a numeric computation, but testing whether a specific computational result is equal to NaN is fraught with peril because any comparison with NaN always yields false except !=, which is always the negation of ==:
nan := math.NaN()
fmt.Println(nan != nan, nan == nan, nan < nan, nan > nan) // “true false false false”
要留心数值和NaN
比较时的返回值。