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?
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
ndo this:If you have a
roundfunction, you can also do the same thing withround(index): subtract $1$ if the result is greater thanindex.If you had neither such an integer type nor any rounding function, you could take the number $1.0$ (if
indexis positive) or $-1.0$ (ifindexis negative) and double it until it is larger in magnitude thanindexis. Let $\pm2.0^n$ be the resulting number after the last doubling. Then perform binary search forindexbetween $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 ofindex. This is somewhat more efficient than simply counting $1.0, 2.0, 3.0, \ldots$ until you find an integer larger thanindex.To even more quickly get a power of $2$ larger in magnitude than
index, start with $2.0$ ($-2.0$ ifindexis negative), and repeatedly square the number (changing sign after each squaring, ifindexis negative) until you find the desired power of $2$.