3 ms·
This is also nice because it gracefully handles the case where `max < min`.
by vortico 6y ago
This is also nice because it gracefully handles the case where `max < min`.
- rags2riches 6y agoIt's not always graceful to say that 1 is both less than 0 and greater than 2.
- vortico 6y agoNot 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.
- resu_nimda 6y agoHe'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.
- vortico 6y agoWhy do you prefer to leave undefined behavior?
- resu_nimda 6y agoI'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.
- tobr 6y agoIn 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.