In pure Python `statistics.median([min, max, num])` also works.
Math.min(Math.max(num, min), max)
81–90 of 291 posts
Re: Math.min(Math.max(num, min), max)
#82I find that the fact that the functions min and max have the same name as the variables min and max increases cognitive load which makes it harder to think about it. I find the following easier to read : Math.min(Math.max(num, lower_bound), upper_bound)
I think this was posted purely for the limerick quality.
near get(), post(), and ajax()
// we alias at import
// to keep all the code short
min(max(number, min), max)
Re: Math.min(Math.max(num, min), max)
#83I find that the fact that the functions min and max have the same name as the variables min and max increases cognitive load which makes it harder to think about it. I find the following easier to read : Math.min(Math.max(num, lower_bound), upper_bound)
Easy to remember, but may take some time to grasp: Arrays.sort( {lower_bound, num, upper_bound} )[1]; Next challenge: teach the optimizer to make that almost as fast as the min/max way ;-) (You can’t reduce it to the min/max call because it also works if you accidentally pass a lower bound that’s larger than the upper bound. Worst-case, the above takes 3 comparisons, unless at least two of the inputs are constants)
I did exactly this for my PhD!
Re: Math.min(Math.max(num, min), max)
#84Earlier quoted context omitted.
sort() on JavaScript arrays sorts alphabetically (unless you pass a compareFunction) https://stackoverflow.com/questions/21019902/why-cant-javasc... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Good point, for those who need to implement a slick compareFunction for numbers, Math.sign is great: [min, num, max].sort((a, b) => Math.sign(a - b))[1] An entirely different alternative is poor man's match: switch (true) { case num > max: return max; case num
.sort((a, b) => a - b)Re: Math.min(Math.max(num, min), max)
#85In languages I use there’s usually no need to write that code. C++/17 has std::clamp() in header. Modern C# has Math.Clamp() since .NET Core 2.0; too bad it’s not available in desktop edition of the runtime. HLSL has clamp() intrinsic function, and a special version saturate() to clamp into [ 0 .. +1 ] interval.
Great. But I have been programming since about 1985.
Re: Math.min(Math.max(num, min), max)
#86Re: Math.min(Math.max(num, min), max)
#87 : clamp ( x min max -- y ) [ max ] dip min ; inline
https://docs.factorcode.org/content/word-clamp,math.order.ht...Re: Math.min(Math.max(num, min), max)
#88Re: Math.min(Math.max(num, min), max)
#89Earlier quoted context omitted.
Seriously. This is about a million times better.
Absolutely. With the above implementation, I can see exactly what's going on, with the others, I'm trying to work out potential edge cases.
Re: Math.min(Math.max(num, min), max)
#90[min, num, max].sort()[1]