Last active
January 12, 2021 09:56
-
-
Save wlbr/9e1035d09d9fc1c1086eef43714857f7 to your computer and use it in GitHub Desktop.
Fun with floating point precision in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"math/big" | |
) | |
func main() { | |
var a, b, c float32 | |
// The bad way | |
a = 0.1 | |
b = 0.2 | |
c = a * b | |
fmt.Println(c) | |
fmt.Println(a * b) | |
// The "with Go don't go that way" way | |
d := 0.1 * 0.2 | |
fmt.Println(d) | |
fmt.Println(0.1 * 0.2) | |
// The good way | |
m := big.NewFloat(0.1) | |
n := big.NewFloat(0.2) | |
var o big.Float | |
//take care that o is of a different type than m and n (big.Float vs *big.Float) | |
o.Mul(m, n) | |
fmt.Println(o.String()) | |
/* ==> | |
0.020000001 | |
0.020000001 | |
0.02 | |
0.02 | |
0.02 | |
*/ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment