Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open the console and create the folder chapter03/recipe02.
  2. Navigate to the directory.
  3. 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)

fmt.Printf("Strings %s = %s equals: %v \n", daStr,
dbStr, dbStr == daStr)
fmt.Printf("Number equals: %v \n", db == da)

// As the precision of float representation
// is limited. For the float comparison it is
// better to use comparison with some tolerance.
fmt.Printf("Number equals with TOLERANCE: %v \n",
equals(da, db))

}

const TOLERANCE = 1e-8
// Equals compares the floating-point numbers
// with tolerance 1e-8
func equals(numA, numB float64) bool {
delta := math.Abs(numA - numB)
if delta < TOLERANCE {
return true
}
return false
}
  1. Execute the command go run tolerance.go in the Terminal.
  2. You will see the following output:
  1. Create the file big.go with the following content:
        package main

import (
"fmt"
"math/big"
)

var da float64 = 0.299999992
var db float64 = 0.299999991

var prec uint = 32
var prec2 uint = 16

func main() {

fmt.Printf("Comparing float64 with '==' equals: %v\n", da == db)

daB := big.NewFloat(da).SetPrec(prec)
dbB := big.NewFloat(db).SetPrec(prec)

fmt.Printf("A: %v \n", daB)
fmt.Printf("B: %v \n", dbB)
fmt.Printf("Comparing big.Float with precision: %d : %v\n",
prec, daB.Cmp(dbB) == 0)

daB = big.NewFloat(da).SetPrec(prec2)
dbB = big.NewFloat(db).SetPrec(prec2)

fmt.Printf("A: %v \n", daB)
fmt.Printf("B: %v \n", dbB)
fmt.Printf("Comparing big.Float with precision: %d : %v\n",
prec2, daB.Cmp(dbB) == 0)

}
  1. Execute the code by running go run big.go in the Terminal.
  2. You will see the following output: