Comparing floating-point numbers
Because of how floating-point numbers are represented, there can be inconsistencies while comparing two numbers that appear to be identical. Unlike integers, IEEE floating-point numbers are only approximated. The need to convert the numbers to a form the computer can store in binary leads to minor precision or round-off deviations. For example, a value of 1.3 could be represented as 1.29999999999. The comparison could be done with some tolerance. To compare numbers with arbitrary precision, the big
package is here.
How to do it...
- Open the console and create the folder
chapter03/recipe02
. - Navigate to the directory.
- Create the
tolerance.go
file with the following content:
package main import ( "fmt" "math" ) const da = 0.29999999999999998889776975374843459576368331909180 const db = 0.3 func main() { daStr := fmt.Sprintf("%.10f", da) dbStr := fmt.Sprintf("%.10f", db) ...