码迷,mamicode.com
首页 > 其他好文 > 详细

3.2

时间:2018-03-22 01:47:42      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:mit   mat   pac   var   for   ret   hex   iso   ring   

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
*/

3.2

标签:mit   mat   pac   var   for   ret   hex   iso   ring   

原文地址:https://www.cnblogs.com/zrdpy/p/8620739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!