Return clamped value when given the numbers nan and -nan(ind) in math.clamp

Since all lua numbers are double-precision integers, we have to deal with the special division by zero numbers. Currently, if you use the function math.clamp(number, min, max) on these numbers, it will output nan or -nan(ind). I am proposing that inputting nan or -nan(ind) as the value to clamp should return either min or max in these cases, like what happens when inputting inf or -inf.

local infs = {0/0, -(0/0), 9e9999, -9e9999}
for _,v in pairs(infs) do
print(v, math.clamp(v, 0, 1))
end

Output:
-nan(ind) -nan(ind)
nan nan
inf 1
-inf 0

What would be the output if this were changed:
-nan(ind) 0
nan 1 (or maybe 0)
inf 1
-inf 0

So essentially treat NaN as infinity? I’m not sure how much sense this makes mathematically, to be fair. The implementation just follows the same rules as C++'s < and > operators right now.

3 Likes

True, but I’d imagine that most people use the clamp function because they want the value to always be within that range without exception. The current workaround would be something like this:

return number == number and math.clamp(number, 0, 1) or 0

I don’t think math.clamp is the best place to deal with NaN, to be honest. How would you choose between the lower bound and the upper bound, for example? I’d prefer to not silently “fix” NaNs because if you have a NaN somewhere then you have a problem you need to address.

8 Likes