在Golang中忽略最后一位比较浮点数。

huangapple go评论99阅读模式
英文:

Comparing floats by ignoring last bit in golang

问题

以下是要翻译的内容:

一个规范如下所示:

> 如果两个实数在最后一个二进制位上不同,它仍然认为它们相等。

我想在Go语言中为float64数据类型实现这种比较浮点数的方式。不幸的是,位运算符对浮点数没有定义。有没有办法在Go语言中实现这种比较浮点数的方式?

英文:

A specification reads as follows:

> It still considers real numbers equal if they differ in their last
> binary digit.

I would like to implement this way of comparing floats for the float64 data type in Go. Unfortunately, the bitwise operators aren't defined for floating point numbers. Is there a way to achieve this way of comparing floats in the Go language?

答案1

得分: 4

这看起来是使用 math 包中的以下函数的完美案例:

func equal(x, y float64) bool {
    return math.Nextafter(x, y) == y
}

Nextafter 函数返回 x 向 y 方向的下一个可表示的 float64 值。

特殊情况包括:
Nextafter(x, x) = x
Nextafter(NaN, y) = NaN
Nextafter(x, NaN) = NaN

链接:https://play.golang.org/p/unRkkoe6wb

英文:

This looks like a perfect use case for the following function from the math package:

func equal(x, y float64) bool {
    return math.Nextafter(x, y) == y
}

> Nextafter returns the next representable float64 value after x towards y.
> <br><br>Special cases are:
> <br>Nextafter(x, x) = x
> <br>Nextafter(NaN, y) = NaN
> <br>Nextafter(x, NaN) = NaN

https://play.golang.org/p/unRkkoe6wb

答案2

得分: 2

如果你想知道两个float64值是否相邻(即它们之间没有其他的float64值),可以使用以下代码:

func almostEqual(a, b float64) bool {
    ai, bi := int64(math.Float64bits(a)), int64(math.Float64bits(b))
    return a == b || -1 <= ai-bi && ai-bi <= 1
}

大多数情况下,这意味着它们在尾数的最低位上有差异。

这段代码在ab为NaN、零或无穷大时无法正常工作,但你可以根据需要添加特殊情况。

参考链接:https://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/

英文:

If you want to know if two float64 values are adjacent (that is, there's no float64 value between them):

func almostEqual(a, b float64) bool {
	ai, bi := int64(math.Float64bits(a)), int64(math.Float64bits(b))
	return a == b || -1 &lt;= ai-bi &amp;&amp; ai-bi &lt;= 1
}

Mostly that's the same as saying they differ in the lowest bit of their mantissa.

This code doesn't work if a or b are NaNs, zeros or infinities, but you could add special cases if you wished.

See https://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/

huangapple
  • 本文由 发表于 2017年9月10日 10:58:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/46136886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定