Go
[Go] The Error of Floating Point Number
llHoYall
2021. 10. 4. 21:19
Like most programming languages, Go also has the floating point error problem.
Problem
Please look at the below code.
package main
import (
"fmt"
)
func main() {
a := 0.1
b := 0.2
c := a + b
fmt.Println(c)
}
// 0.30000000000000004
c was not a 0.3!
Therefore, we are hard to compare floating point numbers.
a := 0.1
b := 0.2
c := 0.3
d := a + b
if c == d {
fmt.Println("It's the same!")
} else {
fmt.Println("It's different!")
}
// It's different!
Them, how can we achieve this?
There are two possible solutions.
Solution1: math.Nextafter()
math package has Nextafter() function.
func Nextafter(x, y float64) (r float64)
Nextafter() function returns the next representable float64 value after x towards y.
if math.Nextafter(c, d) == d {
fmt.Println("It's the same!")
} else {
fmt.Println("It's different!")
}
// It's the same!
Solution2: math/big
math package has the big package and it can handle floating point numbers precisely.
a, _ := new(big.Float).SetString("0.1")
b, _ := new(big.Float).SetString("0.2")
c, _ := new(big.Float).SetString("0.3")
d := new(big.Float).Add(a, b)
if c.Cmp(d) == 0 {
fmt.Println("It's the same!")
} else {
fmt.Println("It's different!")
}
// It's the same!
It's a little complex but if you handle a financial program, you'd like to use this package.
반응형