Re:Math.min(Math.max(num, min), max)
by rags2riches on Thursday August 20, 2020 @12:57PM
(#24225455)
It's not always graceful to say that 1 is both less than 0 and greater than 2.
[ Parent
| on HN ]
Not sure what you mean. If I want to clamp 1 between 2 and 0, the most reasonable answer is 1, which is correctly returned by this code.
Re:Math.min(Math.max(num, min), max)
by resu_nimda on Thursday August 20, 2020 @02:32PM
(#24226767)
He's saying that, if you have explicitly defined a max and min such that max < min, it is not graceful for the computer to produce a result as though those values were swapped. In other words, garbage in should produce garbage out.
The array implementation sidesteps this by not semantically defining a max and min, instead sorting three arbitrary numbers.
In practice “max” and “min” often aren’t conceptually important for a clamp function. It’s more that you want to keep a value within a range, which is defined by two end points in arbitrary order.
If that is the version of clamp you need, the sort based solution reveals something profound and unexpected: it’s not just the two end points of the range that are equivalent, but all three numbers. Keeping value A between B and C is the same as keeping B between A and C or C between A and B. It’s completely arbitrary which pair you consider to be a range.
Why do you prefer to leave undefined behavior?
Re:Math.min(Math.max(num, min), max)
by resu_nimda on Thursday August 20, 2020 @03:53PM
(#24228001)
I'm not sure what you mean. The behavior of the max() and min() functions is perfectly well defined. The terms "maximum" and "minimum" are well defined. If I were using those terms I would likely consider the case where max < min to be an error, or have some other meaning, like an empty range.
If I wanted it to automatically flip the values to ensure a sensible range is defined, I would probably use "a" and "b" or "endpoint1" and "endpoint2" or something, because "max" has now become "max or min," which is not the same.