Asked • 05/07/19

Most efficient/elegant way to clip a number?

Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lower and upper? Of course, using a bunch of if statements can do this, but that's boring! What about more compact and elegant/fun solutions? My own quick attempt (C/C++): float clip( float n, float lower, float upper ) { n = ( n > lower ) * n + !( n > lower ) * lower; return ( n < upper ) * n + !( n < upper ) * upper; } I'm sure there are other, better ways to do this, that's why I'm putting this out there..!

2 Answers By Expert Tutors


Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.


Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.