How to derive the following flooring function?

261 Views Asked by At

I am a programmer and for avoiding floating point precision problem in computing, I found somewhere on the internet the following is the same:

$\lceil\frac{a}{b}\rceil$ = $\lfloor\frac{a+b-1}{b}\rfloor$

While it gives correct results (based on testing), I always forgot this handy formula. So I want to learn the way of deriving this result.

Assuming both $a, b$ are integers. $b > 0$

How can one derive R.H.S. from L.H.S.?

1

There are 1 best solutions below

0
On BEST ANSWER

One way to do it is first observe that: $$\left\lfloor{\frac{a+b-1}{b}}\right\rfloor = \left\lfloor{\frac{a-1}{b}+1}\right\rfloor = \left\lfloor{\frac{a-1}{b}}\right\rfloor + 1$$ since integers can always be "pulled out" of floor/ceiling functions. Thus, the identity to be proved is equivalent to: $$\left\lceil{\frac{a}{b}}\right\rceil = \left\lfloor{\frac{a-1}{b}}\right\rfloor + 1$$

Now, let $q$ and $r$ be the quotient and remainder of the division of $a-1$ by $b$ so that $$a - 1 = q b + r \;\;\; \text{ with } \; 0 \le r \lt b$$

Then:

$$ \frac{a}{b} = q + \frac{r+1}{b} \;\;\; \text{ where } \;0 \lt \frac{r+1}{b} \le 1 \;\;\; \text{ so } \;\left\lceil{\frac{a}{b}}\right\rceil = q + 1 $$

and:

$$ \frac{a-1}{b} = q + \frac{r}{b} \;\;\; \text{ where } \;0 \le \frac{r}{b} \lt 1 \;\;\; \text{ so } \;\left\lfloor{\frac{a-1}{b}}\right\rfloor = q $$

from which the sought equality follows.