# Round to down - Remainder emulation?

I need to Round (to down; so to floor) a double, such as:

base = floor(index)


But I don't have that native/primitive function in the application I'm using. So the best way would be:

base = index-index % 1;


which give to me the same result (if I'm not wrong). Unfortunatly, I'm forced to use only three math operations for double: Add, Multiply and Subtract. I don't have %.

How can I do it?

• You could do $x-i$ for integers $i=1,2,\cdots$ and see when $x-i<0$, in case $x$ is positive (otherwise do something similiar, and check at the start whether or not $x$ is positive). If you have access to round, just rounding to the nearest integer, then you could do round(x-1/2) – vrugtehagel Feb 15 '16 at 14:20
• I could use round(x-1/2). But for int (i.e. tie breaking 0.5) it round ho even (which I don't want; it is not flooring). What do you mean with x-i for integers 1..2? I don't get it... – markzzz Feb 15 '16 at 14:44

If you have an integer type available, and can assign a floating-point number to it, somehow rounding off the fractional part (up, down, nearest, doesn't matter as long as the result is either the integer above or below the floating-point number), and if you can compare integers and floating-point numbers, then for integer n do this:

n = index
if (n > index) then n = n - 1


If you have a round function, you can also do the same thing with round(index): subtract $1$ if the result is greater than index.

If you had neither such an integer type nor any rounding function, you could take the number $1.0$ (if index is positive) or $-1.0$ (if index is negative) and double it until it is larger in magnitude than index is. Let $\pm2.0^n$ be the resulting number after the last doubling. Then perform binary search for index between $0.0$ and $\pm2.0^n$ until the upper and lower bounds of the search are one unit apart. They will then be the floor and ceiling of index. This is somewhat more efficient than simply counting $1.0, 2.0, 3.0, \ldots$ until you find an integer larger than index.

To even more quickly get a power of $2$ larger in magnitude than index, start with $2.0$ ($-2.0$ if index is negative), and repeatedly square the number (changing sign after each squaring, if index is negative) until you find the desired power of $2$.