Module:Math/compare: Difference between revisions
Appearance
Template>Theknightwho No edit summary |
m 1 revision imported |
(No difference)
| |
Latest revision as of 08:44, 29 June 2025
Documentation for this module may be created at Module:Math/compare/doc
local math_module = "Module:math"
local function is_NaN(...)
is_NaN = require(math_module).is_NaN
return is_NaN(...)
end
local function sign(...)
sign = require(math_module).sign
return sign(...)
end
--[==[
A comparison function for numbers, which returns {true} if {a} sorts before {b}, or otherwise {false}; it can be used as the sort function with {table.sort}.
This function is roughly equivalent to the {<} operator, but contains the following special considerations in accordance with the {{w|IEEE 754}} standard:
* {{w|NaN}} is sorted as though it has a larger absolute value than infinity ({-NaN < -Inf}; {+Inf < +NaN}).
* {{w|Signed zero}} is acknowledged, with {-0 < +0}.]==]
return function(a, b)
-- <, > and == canot return true if either `a` or `b` are NaN.
if a < b then
return true
-- Use > then == instead of >=, so that the ±0 check is only done when `a`
-- and `b` are equal.
elseif a > b then
return false
elseif a == b then
-- 1/(+0) is Inf; 1/(-0) is -Inf.
return a == 0 and b == 0 and 1 / a < 1 / b or false
-- One or both must be NaN, and NaN is the only number that returns false
-- to a self-equality check, so if `a` == `a` then `b` is NaN (and vice-
-- versa). -NaN sorts before everything and +NaN after everything, so the
-- sign determines the result.
elseif not is_NaN(a) then -- `b` is NaN
return sign(b) == 1
elseif not is_NaN(b) then -- `a` is NaN
return sign(a) == -1
end
-- If both are NaN, only return true if `a` is -NaN and `b` is +NaN.
return sign(a) < sign(b)
end