Following Go code
for i := 0.0 ; i < 5 ; i+=0.1 {
fmt.Printf("%v, ", i)
}
results in this (partial) output
0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5
Why am I getting 0.30000000000000004 instead of 0.3?
Following Go code
for i := 0.0 ; i < 5 ; i+=0.1 {
fmt.Printf("%v, ", i)
}
results in this (partial) output
0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5
Why am I getting 0.30000000000000004 instead of 0.3?
A binary floating-point number can't hold 1/10 exactly, just like a decimal number with a finite number of digits can't hold 1/3 exactly. When you keep adding 0.1 repeatedly, the errors add up to enough that they show up in your program's output.
The best way to fix this is to use an integer as your loop control variable, and calculate your floating-point value from it at each iteration:
for i := 1; i < 50; i++ {
f := float64(i) / 10
fmt.Printf("%v, ", f)
}
Note that I'm dividing by 10 instead of multiplying by 0.1 (actually by the binary approximation of 0.1).
Short answer: It has to do with how numbers are stored in a computer.
Specifically for GoLang you might want to read "Floating Point Numbers"