Is it possible to limit a value in a given range, between min and max, using only arithmetic? That is, +
-
x
/
and %
?
I am not able to use functions such as min
, max
nor IF
-statements.
Let's assume I have a range of [1850, 1880]
, for any values < 1850
, it should display 1850
. For values > 1880
, 1880
should be displayed. It would also be acceptable if only 1850
was displayed outside the range.
I tried:
x = (((x - xmax) % (xmax - xmin)) + (xmax - xmin)) % (xmax - xmin) + xmin
but it gives different values in the middle of the range for values lower than xmin
.
I found this while messing around in... excel. It only works for strictly positive integers. Although this is not more restrictive as the answer by meowgoesthedog because he also effectivly halves the integer space by dividing by two at the end. It doesn't use mod.
//A = 1 if x <= min
//A = 0 if x >= min
A = 1-(min-min/x)/min
//B = 0 if x <= max
//B = 1 if x > max
B = (max-max/x)/max
x = A*min + (1-A)*(1-B)*x + B*max