Floating Point Precision in Go: float32 vs float64
In Go, floating-point numbers are represented using the IEEE 754 binary format. This format provides varying levels of precision depending on the data type used, with float32 offering less precision than float64.
Consider the following code snippet, which demonstrates浮点数误差:
package main import "fmt" func main() { a := float64(0.2) a += 0.1 a -= 0.3 var i int for i = 0; a < 1.0; i++ { a += a } fmt.Printf("After %d iterations, a = %e\n", i, a) }
When using float64, the program correctly outputs:
After 54 iterations, a = 1.000000e+00
However, if float32 is used instead, the program enters an infinite loop. This is because float32 cannot represent the decimal value 0.1 exactly, resulting in a slightly rounded value. This rounded value prevents the loop from terminating.
To understand this difference, examine the binary representation of the floating-point values involved:
float32(0.1): 00111101110011001100110011001101 float32(0.2): 00111110010011001100110011001101 float32(0.3): 00111110100110011001100110011010 float64(0.1): 0011111110111001100110011001100110011001100110011001100110011010 float64(0.2): 0011111111001001100110011001100110011001100110011001100110011010 float64(0.3): 0011111111010011001100110011001100110011001100110011001100110011
Note that the binary representation of 0.1 in float32 is slightly different from that in float64. This slight difference leads to a different interpretation of the value by the float32 type, resulting in the observed behavior.
In summary, when using float32, the approximate value of 0.1 is stored in memory, which affects the precision and accuracy of floating-point operations. In contrast, float64 can more accurately represent the decimal value 0.1, allowing for more precise calculations.
The above is the detailed content of Go's Floating-Point Precision: Why Does `float32` Cause Infinite Loops While `float64` Doesn't?. For more information, please follow other related articles on the PHP Chinese website!