(I hope) this is not a question about the accuracy of floating point math in Go. Below I have a test function with 2 expressions that I think should produce equal results, but given the inputs, produce different output.
Edit This ended up being just about floating point precision.
package main
import "fmt"
func main() {
fmt.Println(test(10.0, 0.1, 1.0)) // 0.2
fmt.Println(test(10.0, 0.2, 1.0)) // 0.3
fmt.Println(test(10.0, 0.3, 1.0)) // 0.4
fmt.Println(test(10.0, 0.4, 1.0)) // 0.5
fmt.Println(test(10.0, 0.5, 1.0)) // 0.6
}
func test(plays float64, rate float64, value float64) float64 {
// return (value/plays) + rate
return (plays*rate + value) / plays
}
The first expression (value/plays) + rate
prints:
0.2
0.30000000000000004
0.4
0.5
0.6
while the second expression (plays*rate + value) / plays
prints the expected output:
0.2
0.3
0.4
0.5
0.6
Why is this?