zoukankan      html  css  js  c++  java
  • 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 
    ", daStr, dbStr, dbStr == daStr)
    
    	// Numbers are not equal
    	fmt.Printf("Number equals: %v 
    ", 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 
    ", 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
    ", da == db)
    
    	daB := big.NewFloat(da).SetPrec(prec)
    	dbB := big.NewFloat(db).SetPrec(prec)
    
    	fmt.Printf("A: %v 
    ", daB)
    	fmt.Printf("B: %v 
    ", dbB)
    	fmt.Printf("Comparing big.Float with precision: %d : %v
    ", prec, daB.Cmp(dbB) == 0)
    
    	daB = big.NewFloat(da).SetPrec(prec2)
    	dbB = big.NewFloat(db).SetPrec(prec2)
    
    	fmt.Printf("A: %v 
    ", daB)
    	fmt.Printf("B: %v 
    ", dbB)
    	fmt.Printf("Comparing big.Float with precision: %d : %v
    ", 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
    */
    
    
  • 相关阅读:
    常见数据结构图文详解-C++版
    求单链表中环的起点,原理详解
    Qt Creator 整合 python 解释器教程
    Qt 共享库(动态链接库)和静态链接库的创建及调用
    qt creator 中的"提升为..."功能简介
    QT 操作 excel 教程
    网易2017校园招聘算法题c语言实现源码
    c语言版贪吃蛇小游戏
    mysql语法结构
    Spring MVC rest接收json中文格式数据显示乱码
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8620739.html
Copyright © 2011-2022 走看看