3.2

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)

	// While formating the number to string
	// it is rounded to 3.
	fmt.Printf("Strings %s = %s equals: %v \n", daStr, dbStr, dbStr == daStr)

	// Numbers are not equal
	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
}

/*
Parsed integer: 12
Parsed hexadecima: 47
Parsed bin: 1
Parsed float: 12.30000

*/


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)

}

/*
Comparing float64 with '==' equals: false
A: 0.299999992 
B: 0.299999991 
Comparing big.Float with precision: 32 : false
A: 0.3 
B: 0.3 
Comparing big.Float with precision: 16 : true
*/

posted on 2018-03-21 23:59  cucy_to  阅读(119)  评论(0编辑  收藏  举报

导航