Float64 Less() implementation in standard Go library

Issue

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] < x[j] || (isNaN(x[i]) && !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?

Solution

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.

Answered By – Benjamin Barrois

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.