23 ms·
Math.min(Math.max(num, min), max)
- STRML 6y agoThe basic function is simply defined as: function clamp(num, min, max) { return Math.max(min, Math.min(num, max)); } That is, if you don't try to do anything fancy and make any parameters optional. Lodash does and it makes the implementation much more complex. _.clamp(input: number, lower?: number, upper: number): number; https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb70ec9973b66baec0975/lodash.js#L13981 https://github.com/lodash/lodash/blob/ddfd9b11a0126db2302cb7...
- deleted 6y ago[deleted]
- bonoboTP 6y agoOr to make sure it's crystal clear what's going on: function clamp(num, min, max) { if (num > max) return max; if (num < min) return min; return num; }
- matthewmacleod 6y agoSeriously. This is about a million times better.
- mywittyname 6y agoAbsolutely. With the above implementation, I can see exactly what's going on, with the others, I'm trying to work out potential edge cases.
- brandmeyer 6y agoI prefer the min/max-based definition for the same reason: Its easier to work out the edge cases around NaN and comparisons against NaN.
- cogman10 6y agoNaN always returns false on comparisons. So seems pretty straight forward that this would return NaN if NaN is passed in. That doesn't seem unreasonable. (In fact, that's what happens with the min/max approach).
- jaffathecake 6y agoYep, I came to the same conclusion https://twitter.com/jaffathecake/status/1296423819238944768 https://twitter.com/jaffathecake/status/1296423819238944768
- Akronymus 6y agoNow in C# with pattern matching: int clamp(num, min, max) { return num switch { _ when num > max => max, _ when num < min => min, _ => num }; } Or as a lambda: Func<int, int, int, int> clamp = (num, min, max) => num switch {_ when num > max => max, _ when num < min => min,_ => num};
- 52-6F-62 6y agoSpeaking only to JS is there any reason to write it any other way outside of being clever or as a lambda for singular use? I definitely prefer this version. (Assuming any necessary runtime checks are included for a given project)
- chasd00 6y agothose extra newline characters slow down the page load :)
- tobyhinloopen 6y agoYou’re joking right
- beirut_bootleg 6y agoThere are many reasons to forego readability, especially when writing a library: performance, compatibility, requirements, interpreter/compiler optimizations or even cyclomatic complexity. In lodash's case it might even be all of the above, although I can't speak for the intentions of the authors since there are no comments to guide readers through the process. Note GP's link points to what looks like the v3 branch. Check out the latest implementation of clamp, with a few less if statements, and what looks like a NaN check using strict equality if you want your mind blown. https://github.com/lodash/lodash/blob/86a852fe763935bb64c12589df5391fd7d3bb14d/clamp.js#L22-L23 https://github.com/lodash/lodash/blob/86a852fe763935bb64c125...
- robocat 6y agoReading that code it looks to me that: clamp(null) returns 0 clamp(undefined) returns NaN clamp(1, NaN, NaN) returns 0 clamp(1) returns 0 clamp(1, 5, NaN) returns 5 JavaScript is hard to write safe code for.
- css 6y agoVery coincidental I see this post almost immediately after writing the same code: new_poll_rate = \ min( max( 1 / messages_per_second, constants.FASTEST_POLL_RATE ), constants.SLOWEST_POLL_RATE ) I agree with the sentiment, I had to re-read this several times to make sure I got it right.
- bovine3dom 6y agoIf fastest poll rate > slowest poll rate, I think you've got them the wrong way around (or is that the joke?).
- stkdump 6y agoIt seems like they are just have bad names, as their unit probably is seconds not 1/seconds.
- css 6y agoFASTEST_POLL_RATE is 1000hz, SLOWEST_POLL_RATE is 10hz. Thus, FASTEST_POLL_RATE is a smaller number on a per-second basis.
- bovine3dom 6y agoAh, I see - for clarity I'd rename them FASTEST_POLL_RATE -> SHORTEST_POLL_PERIOD or store them in Hz rather than seconds, so everything was 1/ in that little snippet. Thanks for clearing up my confusion :)
- css 6y agoYeah that’s a very good call, I will probably rename these. Thanks for the critique!
- ebg13 6y ago> it takes me ages to convince myself this implementation is correct It would take them less time to convince themself if they switched min and num to put the values in proper semantic order: min < num < max. Math.min(Math.max(min, num), max)
- jaffathecake 6y agoI don't think so. Whereas an if statement is easy to read https://twitter.com/jaffathecake/status/1296423819238944768 https://twitter.com/jaffathecake/status/1296423819238944768
- bhaak 6y agoThat still leaves the order of Math.min and Math.max undecided and will probably not help much if you get easily confused by the visuals of this code. I never thought about it but of course there must be code tongue twisters (or more correctly, brain twisters). Thinking about it, I would probably go with a less confusing implementation. Terse code is hard to read and the compiler is likely clever enough to choose the best implementation anyway.
- hansvm 6y ago> and the compiler is likely clever enough to choose the best implementation anyway. Not in my experience. The compiler is likely to be able to do something decent to it, but it'll probably be different. Consider the following snippets. For unsigned integers they're all equivalent (and return the max of x and m), but gcc with a wide range of flags can't recognize them as identical. (x<m) * m + (x>=m) * x (x<m) * (m-x) + x x<m ? m : x
- bhaak 6y agoThere can always be things that trip the compiler. Without looking at the actual assembler, you never know that. Interestingly in your example, clang is able to resolve the first and the third line to the same assembler code. https://godbolt.org/z/navMEc https://godbolt.org/z/navMEc I do wonder why it then isn't able to do that for the second line. Possibly because the CPU might have different flags set after processing the substraction? But I'm not sure if your example is a good argument after I said I prefer less confusing code and you present an example which even confuses the compiler. ;-)
- rewq4321 6y agoStage 1 ECMAScript proposal to add Math.clamp (among others): https://github.com/rwaldron/proposal-math-extensions https://github.com/rwaldron/proposal-math-extensions But it looks dead: https://github.com/rwaldron/proposal-math-extensions/issues/16 https://github.com/rwaldron/proposal-math-extensions/issues/... As someone mentioned in the thread, nested ternary is easier to interpret: (a > max ? max : (a < min ? min : a))
- jaffathecake 6y agoI don't find this a whole lot easier to read to be honest. It seems like doing minification manually, when we have tools to do that for us. An if statement seems a lot clearer, and minifies well https://twitter.com/jaffathecake/status/1296423819238944768 https://twitter.com/jaffathecake/status/1296423819238944768
- balfirevic 6y agoIt's just a matter of what you're used to. Both of those are equally clear to me.
- macspoofing 6y agoTo each his own but I disagree. Nested ternary's are hard to read and understand, and modifying them (by future devs) is tricky and error prone.
- deleted 6y ago[deleted]
- Stratoscope 6y agoTrue, nested ternaries can be hard to follow. And the excessive parentheses promote this way of looking at it. OTOH I think chained ternaries can be simple and easy to understand. Yes, they are the exact same thing in this case, but getting rid of those nested parens really helps, at least for me. sarah180's example is a good illustration. I would change the order of the tests because it makes more sense to me to check the min before the max. I'd also make one minor formatting change, because I code in a proportional font and can't line things up in columns: a < min ? min : a > max ? max : a Maybe people think differently, but to me that is super easy to understand, and much better than the confusing Math.min/max stuff. I would also wrap the whole thing inside a function: function clamp( value, min, max ) { return( value < min ? min : value > max ? max : value ); } Now that it's inside a function, you could change the code to use if statements, or Math.min/max, or whatever suits your preferences.
- mauricio 6y agoAlways good to know the underlying implementation, but for any Ruby readers check out clamp(). It's been available since 2.4. 25.clamp(5, 10) => 10 6.clamp(5, 10) => 6 1.clamp(5, 10) => 5
- madcaptenor 6y agoI find myself needing this most frequently in making graphics in R. The scales package has squish() with the same behavior: squish(25, c(5, 10)) => 10 squish(6, c(5, 10)) => 6 squish(1, c(5, 10)) => 5 If you don't provide the limits it defaults to c(0, 1). That's because this function exists to map to a 0-to-1 range for functions that then map the [0, 1] range to a color ramp.
- chrisseaton 6y agoI often see [a, b, c].sort[1] which I think is very neat.
- stickyricky 6y agoYes but its too many operations for such a simple problem. No need to overwork the system when two conditionals can solve the problem.
- rubber_duck 6y agoI'd say the only way this would be better than min/max solution is that you can't accidentally flip it when writing the code - but IMO both suck at expressing intent, clamp reads unambiguously.
- nitrogen 6y agoIf you are writing code that is clamping a lot of numbers, the GC churn from building a new array every time might be a problem.
- chrisseaton 6y agoIdeally the temporary array should optimise away.
- Const-me 6y agoIn languages I use there’s usually no need to write that code. C++/17 has std::clamp() in <algorithm> 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.
- the-dude 6y agoGreat. But I have been programming since about 1985.
- Const-me 6y agoI’ve been programming for living since 2000, but I don’t think that’s relevant. No reason not to use what’s available in standard libraries of whatever language you’re writing. For example, C++ on AMD64 is very likely to compile std::clamp<double> into 2 instructions, minsd and maxsd. I’m not so sure about nested ternaries mentioned elsewhere in the comments.
- naikrovek 6y agoThere are very good reasons to avoid std:: stuff. And if you don't already know that in your soul, I will appear to be a genuine crackpot, and the reasons not to use std::* will still exist.
- kcb 6y agoAre you saying a C++ developer shouldn't use the standard library?
- Tuna-Fish 6y agoNot the person you are replying to, but "a lot of the standard library is horrifying and should never be touched" is pretty standard advice for C++. Mind, I don't think this particular function belongs to that set.
- tobr 6y ago[min, num, max].sort()[1]
- tosh 6y agosort() on JavaScript arrays sorts alphabetically (unless you pass a compareFunction) https://stackoverflow.com/questions/21019902/why-cant-javascript-sort-5-10-1 https://stackoverflow.com/questions/21019902/why-cant-javasc... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- tobr 6y agoVery good point. I thought of it more as pseudocode.
- tosh 6y agoimho a very elegant solution and probably works in most languages, I was surprised by JavaScript's behaviour myself
- 1-more 6y agoFor a real fun headscratcher consider [ '9', '10', '11', '12', '13' ].map(parseInt)
- yboris 6y agoThank you for this exercise! I figured it out! [ROT 13] spoiler: cnefrVag frpbaq nethzrag vf onfr, znc frpbaq nethzrag vf vaqrk va neenl. 10 vf gur frpbaq nethzrag, vaqrk 1. cnefrVag(10, 1) unf vyyrtny onfr [0] https://rot13.com/ https://rot13.com/
- tgb 6y agoWait, really? I just had to double-check my one JS project for bugs and either I used to know this gotcha or I got lucky. My sort()-ing needed to handle NaNs carefully so I was already using custom comparators.
- OscarCunningham 6y agoIdeally I'd also want to throw an error when max < min.
- patresh 6y agoI 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)
- boxfire 6y agoI think this was posted purely for the limerick quality.
- hanoz 6y agoThere was a young coder whose hacks His manager often claimed lacked The requisite clarity For to clamp vars would he: Math.min(Math.max(number, min), max);
- drbacon 6y ago@jaffathecake had a problem of truncation and posted to Twitter his calculation. The gist of his attack was min( max( num, min ), max) yet refused to add any annotation.
- deleted 6y ago[deleted]
- jkaptur 6y agoIn a file of utility hacks near get(), post(), and ajax() // we alias at import // to keep all the code short min(max(number, min), max)
- gmfawcett 6y agoHaiku is nice, too: Cryptic sorcerer! "Math.min(Math.max(v, min), max);" his incantation.
- Dylan16807 6y agoThat doesn't really help. "Max" to enforce a "lower bound" is briefly halting.
- spapas82 6y agoHere's clamp in idiomatic Elixir (using multi-clause functions and guards): def clamp(min, _max, n) when n<min, do: min def clamp(_min, max, n) when n>max, do: max def clamp(_min, _max, n), do: n
- grantjpowell 6y agoAn Elixir convention I've seen is to put the thing you're operating on first, so that you can compose functions using the `|>` operator, which places the previous expression as the first argument of the function to the right. Maybe something like this? defmodule Compare do def clamp(number, minimum, maximum) do number |> max(minimum) |> min(maximum) end end import Compare clamp(5, 1, 10) # 5 clamp(1, 5, 10) # 5 clamp(10, 1, 5) # 5 some_number |> clamp(min, max) As a side note, I think the Elixir |> operator is a stroke of genius that other languages should take a look at. Making the pipe operator append the _first_ argument has the following benefits 1.) It makes the most "important" argument of the function the first thing you read in function signatures 2.) If you need to add more arguments to a function signature later, they tend to be less important the original args, so they tend to make sense at the end 3.) It creates a convention for all libraries to follow so they can leverage the pipe operator. Its really jarring when the thing you want to put in a pipeline isn't the first argument (looking at you `Regex`[0] which puts the regular expression as the first arg and not the string) [0] https://hexdocs.pm/elixir/Regex.html#replace/4 https://hexdocs.pm/elixir/Regex.html#replace/4
- spapas82 6y agoYes you are right! Puting the number in the first parameter is even more idiomatic Elixir.
- LandR 6y ago> It makes the most "important" argument of the function the first thing you read in function signatures Doesn't that make writing functions that can use partial application harder? e.g. If I was writing clamp i would want the signature to be (defn clamp [min max n] ,,,) Then I can do: (map (partial clamp 1 11) [-14 2 5 8 11 15 18]) I know when I use Clojures threading macros I use thread last way more than any of the others. My next most common would be piping it into arbitrary locations, e.g.: ; pipe into an arbitrary spot (specified here as o) (as-> (range 1 10) o (map inc o) (filter even? o) (reduce + o)) I rarely use thread-first.
- fouric 6y agoDo people actually have trouble with this repeatedly, or just when they first learn about it? I started using this implementation of clamp a few years ago, and while it gave me some trouble when I first implemented it, the pattern is very simple, and I got used to it very quickly. I use Common Lisp: > (max min (min max n)) Is the difference my choice of language, my personal mental hardware, the amount of familiarity one has with the pattern, or none of the above?
- tosh 6y agoin k: xs: 1 2 3 4 5 max: 4 min: 2 max& min| xs 2 2 3 4 4 works for scalar, vector, matrix
- Jtsummers 6y agoAfter some of the recent J posts I spent a bit of time refreshing myself on it: max <. min >. nums or equivalently: min >. max <. nums
- uryga 6y agoK made me realize that if you use the numbers 0 and 1 for booleans, `min()` is `&&` and `max()` is `||`. love that!
- tosh 6y agosame here, illuminating a-ha moment!
- donquichotte 6y agoLuckily, this is a solved problem for go. func helper(a float64, c chan float64){ time.Sleep(time.Duration(a) * time.Second) c <- a } func clamp(a float64, min float64, max float64) float64 { c := make(chan float64, 3) go helper(a, c) go helper(min, c) go helper(max, c) _, out, _ := <-c, <-c, <-c return out }
- ccmcarey 6y agoThat will give you the median value. What OP wants is the value `a` clamped within `min` and `max`.
- donquichotte 6y agoCan you give an example where median([a, min, max]) is not equal to clamp(a, min, max), given max >= min?
- naikrovek 6y agoIf a < min or a > max, if I'm reading it right.
- mc10 6y agoYou can prove that this algorithm works for both of those cases. Assuming min <= max: If a < min, then the sorted array is [a, min, max]. The median is min, which is a clamped to min. If a > max, then the sorted array is [min, max, a]. The median is max, which is a clamped to max.
- apta 6y agoaka sleep sort
- tl 6y agoPassing math.NaN() crashes in a playground.
- 6y ago
- w-m 6y agoI personally would find this much more straightforward: val - (sign(val - max) + 1) / 2 * (val - max) + (sign(min - val) + 1) / 2 * (min - val)
- deleted 6y ago[deleted]
- 9nGQluzmnq3M 6y agoNot as elegant, but way more readable: if num > max: num = max if num < min: num = min
- deleted 6y ago[deleted]
- throwawaw 6y agoFun seeing that pretty much everyone else finds that idiom confusing too. Half-serious, over breakfast: (case [(> n min) (< n max)] [true true] n [true false] max [false true] min) (Side note: Clojure's `>` and `<` are kind of unreadable to begin with. Turning `if (> n min)` into "if n is greater than min" takes some work for me, still, after more than a year.)
- retzkek 6y agoHowever, prefix notation becomes much easier to read and reason about when you have more than two things to compare: (> 3 2 1 ...) vs (3 > 2) && (2 > 1) && ...
- kickopotomus 6y agoAlternatively, since min and max are part of clojure.core: (-> n (max vmin) (min vmax))
- white-flame 6y agoWhat about the [false false] case where min ≥ n ≥ max?
- LandR 6y ago> (Side note: Clojure's `>` and `<` are kind of unreadable to begin with. I felt the same for awhile but now I just mentally put the operator between the operands, so (> 3 2) is the same as 3 > 2.
- ragnese 6y agoThis one doesn't bother me much. What's harder and worse, IMO, is doing saturating math.
- lalaithion 6y agoThis is a great example of how haskell makes these things obvious ;) clamped = num `max` min' `min` max'
- graham_paul 6y agono idea what's going on there, I know some of those variables are actually functions but the whole thing is unreadable unless you have experience in haskell imo
- masklinn 6y agoThe backticks turn regular functions into left-associative operators of the highest priority (by default). So a `foo` b `bar` c is (bar (foo a b) c)
- O_H_E 6y agoOohh nice. So kinda like a pipe. I really think we deserve more syntax that allowed something like this, because otherwise one needs to read `(bar (foo a b) c)` inside-out.
- masklinn 6y ago> Oohh nice. So kinda like a pipe. I never thought of it that way, but it is true that it can be used as a pipe. Fundamentally it's just the dual of (): Haskell lets you use operators as infix functions by wrapping them in () so (+) 1 2 is the same as 1 + 2 and conversely lets you use prefix (binary) functions as operators by wrapping them in backticks. You can even combine those through sections, which serve to partially apply infix operators: https://wiki.haskell.org/Section_of_an_infix_operator https://wiki.haskell.org/Section_of_an_infix_operator
- parliament32 6y agoPython also doesn't have a built-in clamp function (I think there might be one in numpy), I usually use sorted((floor, x, ceiling))[1] Throw it in a function with some asserts if you're worried about x not being a number and giving you weird results.
- kazinator 6y agoThis is the TXR Lisp interactive listener of TXR 242. Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet. 1> (clamp 1 10 -1) 1 2> (clamp 1 10 15) 10 3> (clamp 1 10 5) 5 Added on August 13, 2015 by commit f2e197dcd31d737bf23816107343f67e2bf6dd8e
- occamrazor 6y agoNumpy has `np.clip`. In pure Python `statistics.median([min, max, num])` also works.
- Haga 6y agoinLimits(lowerBound, Val, upperBound)
- gre 6y agoIn Factor: : clamp ( x min max -- y ) [ max ] dip min ; inline https://docs.factorcode.org/content/word-clamp,math.order.html https://docs.factorcode.org/content/word-clamp,math.order.ht...
- cjallen88 6y agoFor casual readers, `dip` pops the top of the stack, executes a quotation, then pushes the top of the stack back on. So this pops the max value off the stack, applies the quoted `max` word to the x and min stack values, then pops the max value back on the stack and applies the `min` word to the result and the max.
- edparcell 6y agoIt is simpler if you use the notation [x]_a^b (i.e. with a subscript and a superscript b) to mean x, clipped to the range a to b, and skip writing +/- infinity if you don't intend clipping on one side. Then you get a bunch of obvious identities like [x]^b = min(x, b) = [b]^x (x capped by b is the same as the smaller of x and b which is the same as b capped by x), [x]_a^b = [b]_a^x, and [x]_a^b = [[x]_a]^b. Putting these together you get [x]_a^b = [[x]_a]^b = min(max(x, a), b). But honestly it's just easier to stick to the notation most of the time. A better write-up, for everyone who doesn't like reading new math notations inline: https://imgur.com/gallery/593QEow https://imgur.com/gallery/593QEow (Imgur link with white background) https://quicklatex.com/cache3/71/ql_46c49ac709b3789482d0736d80481871_l3.png https://quicklatex.com/cache3/71/ql_46c49ac709b3789482d0736d... (Original link - renders badly in Chrome due to PNG transparency)
- secondcoming 6y agoThose are all valid C.
- bigganibba69 6y agoDamn, this dude is one condescending shitcoder lmao
- polote 6y ago> it takes me ages to convince myself this implementation is correct. > Googler Then this is another proof that google doesnt only hire on mathematical puzzle tricks
- aldanor 6y agoOnce you've seen this a few dozen times, you instantly parse it as "clamp(num, min, max)"
- hombre_fatal 6y agoDid a bunch of coding bootcamps just begin session or something? I don't understand the comments here treating it like it's so hard to write and verify that it needs a completely different, slower, less direct, cutesy implementation.
- aldanor 6y agoI don't understand the explosion of comments here either. I was just saying for myself, it's a trivial construct and very commonly encountered.
- slifin 6y agoI'm not sure why the author isn't putting his preferred implementation into a clamp function then forgetting about it?
- pachico 6y agoI would make it more confusing to read by using the 100 and 0 percentiles.
- nibbapower69 6y agoThe author is one condescending shitcoder lmao
- moralestapia 6y ago>[...] it takes me ages to convince myself this implementation is correct. Is that supposed to be difficult? Not trying to be snarky, I'm honestly surprised, do people actually struggle with this? Googlers in particular?
- im3w1l 6y agoTook me a few minutes first time I saw it but it's now firmly in my mental library of idioms.
- young_unixer 6y agox2 While doing competitive programming I learned that I'm really stupid, but even as stupid as I am, I still understand that expression easily.
- dgb23 6y agoThis whole discussion feels like I‘m not getting an obvious joke.
- jodrellblank 6y agoDo people actually struggle with not being snarky to the point where they have to explicitly say that, and still come across as snarky?
- tzs 6y ago68K assembly, no branches: # d0 = num, d1 = low, d2 = high, d3 = scratch sub.l d1, d0 subx.l d3, d3 or.l d3, d0 addx.l d1, d0 # d0 = max(num,low) sub.l d2, d0 subx.l d3, d3 and.l d3, d0 add.l d2, d0 # d0 = min(max(num,low),high) Adapted from "Superoptimizer -- A Look at the Smallest Program" by Henry Massalin [1]. [1] https://web.stanford.edu/class/cs343/resources/superoptimizer.pdf https://web.stanford.edu/class/cs343/resources/superoptimize...
- kazinator 6y agoIsn't .l implied if it is omitted? If I just say "sub d1, d2", of course I mean the whole register width, and not just 16 or 8 bits of it.
- saagarjha 6y agoNote that with modern branch predictors such optimizations may not actually be beneficial–ARM got rid of condition codes on all its instructions in the 64-bit version. (Plus, I assume they ran out of space to encode them.)
- brandmeyer 6y agoIEEE754 has defined min and max for quite some time. Nowadays almost all FPUs have min and max instructions built-in.
- V-2 6y agoKotlin provides pretty nice syntax sugar for that: num.coerceIn(min..max) That's it. This human reader finds it considerably more readable. It also has coerceAtLeast and coerceAtMost
- nitrogen 6y agoDoes kotlinc optimize away inline ranges like that, or does this result in a range object being constructed and discarded?
- RandomBK 6y agoI haven't heard of any instances of Kotlin itself optimizing these things away, but the JVM may be able to do so during its various JIT passes. It's definitely not something you can necessarily rely on, though. Luckily, these convenience methods are usually implemented as inline extension functions, so the whole thing will get inlined into the calling method, making JIT optimization more likely.
- sanbor 6y agoThis is what I love about kotlin. The standard library has a good coverage of these kinds of problems and it is done in a simple an clean way. I had the same feeling with Python, the language got you cover with mundane tasks and you don't have to spend time researching libs that do it for you (or spend your time doing a clamp implementation + tests).
- Imnimo 6y agoOn the one hand, I've done this enough times that I can usually write it on auto-pilot without thinking about it. But on the other hand, whenever I make a mistake, the resulting bug is really hard to track down, because it's tough to just stare at the line and recognize that something wrong.
- O_H_E 6y agoI always though pipe operators are under-rated and under-used. In elixer that could be
- deleted 6y ago[deleted]
- O_H_E 6y agoI think the main hurdle is that we need to read this inside-out, which is something we face regularly trying to read nested function calls. I seriously believe pipe-like operators solve this problem cleanly. In Elixir which does have the pipe `|>` this could be. number = number |> max(lower_bound) |> min(upper_bound) Which IMO is quite elegant.
- deleted 6y ago[deleted]
- beervirus 6y agoIs this a problem that comes up often? What kind of situation would make you want to calculate this?
- baddox 6y agoIt's common in computer graphics and user interface programming. You want to move your character around a 2D grid, but you don't want either of its x and y coordinates to ever move outside the bounds of the 2D grid. Or you want a web page with an article section that is 50% of the browser width, but never narrower than 300px and never wider than 800px.
- mr_toad 6y agoIt’s pretty common in data science or financial applications to restrict the range of data in this way. There are probably SQL devs reading this and wondering what the fuss is about.
- geophile 6y agoOPs implementation requires 2 comparisons. I think this C expression is clearer, and will sometimes use 1 comparison: num < min ? min : num > max ? max : num
- deleted 6y ago[deleted]
- xondono 6y agoTo me the danger of this kind of one liners is that if you use it 2 times somewhere, someone, at some point, will do the lazy refactor of “let’s put it into a function”. int clamp (int value, int min, int max) And that one liner inside. And now you have a double evaluation bomb waiting to go out on your codebase.
- geophile 6y agoWhy? You wrote a function, not a macro.
- xondono 6y agoAccidentally overwrote the middle step: Junior developer puts the one liner on google, finds the typical macro definition and does the change.
- adrianmonk 6y agoMaybe they mean that you might have been unintentionally relying on double evaluation, and then you take it away, and something breaks. Because it worked for the wrong reasons.
- edflsafoiewq 6y agoIncidentally, gcc and clang both compile this to two cmovs for me.
- geophile 6y ago
- antoineMoPa 6y agoWhen making glsl shaders, there's clamp().
- wonderlg 6y agoThere’s an obvious solution to this: require('clamp')(num, min, max) 1 million monthly downloads
- ossopite 6y agoExcel has no clamp function but a neat alternative is =MEDIAN(min, num, max)
- LifeLiverTransp 6y agocommunicate by structure what it does.. clamp(lowerBound, val, upperBound)
- jchw 6y agoI always used to get confused by the function names “min” and “max” because they return the minimum and maximum, but typically when you use them you are thinking in terms of applying a minimum or maximum bound. Having a dedicated clamp function significantly helps although imo there is not a single correct order for the parameters to go in.
- z3ncyberpunk 6y agoMore often than not no.. I am trying to find the min/max value in a set. Bit a bound
- da39a3ee 6y agohttps://twitter.com/ben_a_adams/status/1296463312780251136 https://twitter.com/ben_a_adams/status/1296463312780251136
- ridiculous_fish 6y agoMost of the ternary implementations here are less correct than the original. You generally want min/max to satisfy the following: 1. min/max of NaN and anything is NaN 2. negative 0 is strictly smaller than positive 0 it's a fun exercise to implement clamp under these constraints.
- ChrisLomont 6y agoI find the following much easier to read. It's certainly easier to maintain, deal with, for successive programmers, and likely has exactly the same compiled/interpreted operations for most common languages. Optionally replace t1 and t2 by overwriting num if needed. Use full if else if you must. If you're worried about speed, using built in min and max is not a good idea. There are many, many tricks to remove branches for certain datatypes, etc., as you need. var t1 = num < min ? min : num; // clamp to min var t2 = max < t1 ? max : t1; // clamp to max return t2; // num clamped to [min,max]
- rkagerer 6y agoWrap it in a function, verify the implementation once, then henceforth use clamp(x, min, max).
- kaiken1987 6y agoAn amusing anecdote ruined by the fact that everyone who can relate immediately starts thinking of a better way to rewrite it. Yes brain that might be better but that's not the joke.
- sanbor 6y agoKotlin implementation [1]: public fun Int.coerceIn(minimumValue: Int, maximumValue: Int): Int { if (minimumValue > maximumValue) throw IllegalArgumentException("Cannot coerce value to an empty range: maximum $maximumValue is less than minimum $minimumValue.") if (this < minimumValue) return minimumValue if (this > maximumValue) return maximumValue return this } [1] https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/coerce-in.html https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/c...
- throwaway6734 6y agoThis is something that upon seeing I would sketch out. It's way easier for me to understand visually
- aaron695 6y ago> it takes me ages to convince myself this implementation is correct. So never use it in code.
- sujitnair 6y agoI find the following easier to visualize. If L is the lower bound and U is the upper bound, and if you visualize L, U as two points on the real number line, then: left_of_U ( right_of_L (num)) = right_of_L ( left_of_U (num)) = clamped version of num between L and U. Here, left_of_U = Math.min(num, U) and right_of_L = Math.max(num, L).
- aabbcc1241 6y agoJust write a isBetween(low,middle,high)
- abiogenesis 6y agoYour method name and the signature are misleading. First, it implies that it returns a boolean, not a number. Second, the argument names look like they have to be already sorted, which defeats the purpose.
- chewbaxxa 6y agoMath.min(a, x) == at_most_a(x) Math.max(b, x) == at_least_b(x) at_most_b(at_least_a(x)) A similar kind of thing is really common in measure theory (limsup, liminf) and option payoffs.
- euske 6y agoIn Python, I usually put the following aliases: upperbound = min lowerbound = max Use: a = upperbound(a, 10) b = lowerbound(-10, b)
- jodrellblank 6y agoIn APL: lower⌈ upper⌊ numbers See a stream of random numbers flowing from right to left. See the higher ones being pushed down ⌊ to the upper bound, and the lower ones being pushed up ⌈ to the lower bound, and the middle ones flowing through both guards unchanged.
- deleted 6y ago[deleted]
- migueloller 6y agoI like doing `Math.max(min, Math.min(num, max))` since it puts them in sort order.
- voldacar 6y agoThe fact that you need to type 33 characters to define something so simple as clamp() really does not make sense
- todorov84 6y agoFor maximum readability, you could also go for (min + ((num + max - Math.abs(num - max)) / 2) + Math.abs(min - ((num + max - Math.abs(num - max)) / 2))) / 2 Since min(a, b) = (a + b - |a - b|) / 2 and max(a, b) = (a + b + |a - b|) / 2
- forth_fool 6y agoTalking about obscurity of code, in Forth you would write: 5 9 7 min max . This prints 7, as it's between 5 (lower bound) and 9 (upper bound). Defining a clamp "function" looks like this: : clamp ( min max n -- clamped_n ) min max ;
- sktguha 6y agoI made a simple clamp function based on this const clamp = (num, min=0,max=100) => Math.min(Math.max(num, min), max)
- HaGoijer 6y agoSlightly offtopic, but very practical use of a comparable algorithm is to determine to what extent a date ranges falls between a first and last date (e.g. first date of the year, last date of year). e.g. in Excel it would look like: MAX((MIN(end date range; last date) - MAX(Start date range;first date) + 1);0)/(last date - first date + 1). This results in 0 in case of no match, a fraction when only a part of the date range falls between the first and last date, and 1 in case it matches completely or even exceeds the first and last date.