I wrote a program to demonstrate floating point error in Go:
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
", i, a)
}
It prints:
After 54 iterations, a = 1.000000e+00
This matches the behaviour of the same program written in C (using the double
type)
However, if float32
is used instead, the program gets stuck in an infinite loop! If you modify the C program to use a float
instead of a double
, it prints
After 27 iterations, a = 1.600000e+00
Why doesn't the Go program have the same output as the C program when using float32
?