# Go语言的浮点型比较大小及其函数式编程魅力

henrylee2cn · · 5254 次点击 · · 开始浏览

``````import (
"fmt"
"math"
)

func main() {
// 设置精确度为0.00001
var a Accuracy = func() float64 { return 0.00001 }
fmt.Println(a.Equal(0.11111222, 0.11111222233333)) //打印结果为：true
}

type Accuracy func() float64

func (this Accuracy) Equal(a, b float64) bool {
return math.Abs(a-b) < this()
}

func (this Accuracy) Greater(a, b float64) bool {
return math.Max(a, b) == a && math.Abs(a-b) > this()
}

func (this Accuracy) Smaller(a, b float64) bool {
return math.Max(a, b) == b && math.Abs(a-b) > this()
}

func (this Accuracy) GreaterOrEqual(a, b float64) bool {
return math.Max(a, b) == a || math.Abs(a-b) < this()
}

func (this Accuracy) SmallerOrEqual(a, b float64) bool {
return math.Max(a, b) == b || math.Abs(a-b) < this()
}``````

0 回复

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

``````import (
"fmt"
"math"
)

func main() {
// 设置精确度为0.00001
var a Accuracy = func() float64 { return 0.00001 }
fmt.Println(a.Equal(0.11111222, 0.11111222233333)) //打印结果为：true
}

type Accuracy func() float64

func (this Accuracy) Equal(a, b float64) bool {
return math.Abs(a-b) < this()
}

func (this Accuracy) Greater(a, b float64) bool {
return math.Max(a, b) == a && math.Abs(a-b) > this()
}

func (this Accuracy) Smaller(a, b float64) bool {
return math.Max(a, b) == b && math.Abs(a-b) > this()
}

func (this Accuracy) GreaterOrEqual(a, b float64) bool {
return math.Max(a, b) == a || math.Abs(a-b) < this()
}

func (this Accuracy) SmallerOrEqual(a, b float64) bool {
return math.Max(a, b) == b || math.Abs(a-b) < this()
}``````