I'm trying to clamp a number to the lower value of a series of numbers. For instance, if I have a series (sorry for the bad notation)
[pq]
where p
is any integer and q
is any positive number.
Say if q is 50
my series will be ...-150, -100, -50, 0, 50, 100, 150...
Now what I'd like is to have a function f(y)
which'll clamp any number to the next lowest number in the series.
For example, if I had the number 37
I'd be expecting the f(37) = 0
and I'd be expecting f(-37) = -50
.
I've tried many algorithms involving modulus and integer division but I can't seem to figure it out. The latest I've tried is for example
(37 / q) * q
which works great for positive numbers but doesn't work for any number between -50 and 0.
I've also tried ((37 - q) / q) * q
but this won't work for negative cases which land exactly in the series.
EDIT
Assume that I do not have the entire series but only the multiplier p
of the series.
You simply need to divide y
by q
using integer Euclidean division and then multiply the result by q
again.
f(y) = (y / q) * q
where /
represents Euclidean division.
In programming languages that do not immediately support Euclidean division you will have to either implement it manually or adjust the result of whatever division the language supports.
For example, in C and C++ Euclidean division for positive divisor q
can be implemented through the native "Fortran-style" division as
(y >= 0 ? y : y - q + 1) / q
so in C or C++ the whole expression will look as
f(y) = (y >= 0 ? y : y - q + 1) / q * q
For 37
you get
f(37) = 37 / 50 * 50 = 0
For -37
you get
f(-37) = (-37 - 50 + 1) / 50 * 50 = -86 / 50 * 50 = -50