标准Go库中Float64 Less()的实现

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

Float64 Less() implementation in standard Go library

问题

我一直在研究Go标准库中的'sort'包,研究所使用的排序算法的具体实现,有一件事对我来说似乎非常奇怪 - Float64 Less()函数的定义

func (x Float64Slice) Less(i, j int) bool { return x[i] < x[j] || (isNaN(x[i]) && !isNaN(x[j])) }

我相当确信,浮点数值(至少在IEEE 754语义中)不应该直接进行比较。为什么标准的Go库中实现的比较是这样的呢?

英文:

I've been digging in 'sort' package of standard Go library, studying concrete implementations of used sorting algorithms and one thing seems really strange to me - definition of Float64 Less() function:

func (x Float64Slice) Less(i, j int) bool { return x[i] &lt; x[j] || (isNaN(x[i]) &amp;&amp; !isNaN(x[j])) }

I quite confident, that floating-point values (in IEEE 754 semantics, at least) MUST NOT be compared directly. Why the comparison implemented this way is in standard Go lib?

答案1

得分: 4

我认为你误解了浮点数不能直接进行比较的含义。

在这个上下文中是正确的:如果你拿两个浮点数,对它们进行不同的计算,数学上得到相同的结果,那么结果很有可能不相等,所以依赖浮点计算来检查数学相等性是一个非常糟糕的想法。

然而,对浮点数切片进行排序是完全有意义的:它们是可比较的,它们有一个顺序。这可能是一个好主意,也可能是一个坏主意,这取决于你的用例是什么。

如果你的用例只是对输入的浮点数据进行排序,那么没有问题。

如果你的用例涉及到一个密集区间的数学问题,那么这可能是一个坏主意。

无论如何,只要记住检查浮点数的相等性通常是一个糟糕的主意,但是比较两个浮点数可能是有意义的,否则你将无法通过比较它们来做出任何决策,而你经常需要这样做。

英文:

I think you misinterpreted that floating-point values must not be compared directly.

This is true in this context: if you take two floating-point numbers, run different calculations on both which mathematically give the same results, then there are lot of chances that the resulting numbers are not equal, so relying on floating-point computation to check mathematical equality is a very, very bad idea.

However, it is perfectly sensed to sort a slice of floating-point numbers: they are comparable, they have an order. This can be either a good or a bad idea, depending on what is your usecase.

If your usecase is just to sort input floating-point data, then there is no problem.

If your usecase is related to a mathematical problem in a dense interval, this is probably a bad idea.

Anyways, just remember that it is generally a bad idea to check for floating-point equality, but comparing two floating-point numbers may have sense, otherwise you could never take any decisions by comparing them, and you often have to do that.

huangapple
  • 本文由 发表于 2022年1月29日 06:26:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/70900972.html
匿名

发表评论

匿名网友

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

确定