Блог пользователя TryOmar

Автор TryOmar, история, 2 года назад, По-английски

Well, instead of using built-in functions in the language it's better if you know how they work and use them in your own way manually

I wondered how the ceil and floor function works, especially in the division $$$\frac{a}{b}$$$.

One of my friends advised me to use this formula to find the ceil(a, b) $$$\lceil \frac{a}{b} \rceil = \frac{a + b - 1}{b}$$$ so in code : int ceil = (a + b - 1) / b; this works perfectly fine with positive $$$a/b$$$

But unfortunately, this formula is not accurate, as it does not work with negative numbers

Here is a counter example $$$\lceil \frac{-6}{2} \rceil = -3$$$ but with this formula we get different result $$$\frac {-6+2-1}{2}$$$ = $$$\frac {-5}{2} = -2.5$$$, so we can't rely on this with negative numbers

Now let's focus on floor for a bit, you maybe think floor(a,b) is so simple as int floor = (int)(a/b);

And I believed it and was happy because it is so simple. But the misunderstanding happened because I used to think that division of integers $$$\frac{a}{b}$$$ in programming is equal to rounding down the result $$$\lfloor \frac{a}{b} \rfloor$$$

While the right was Truncating division Truncating division is division where a fractional result is converted to an integer by rounding towards zero.

Or in another way integer division is just omitting the fraction part not flooring the value so we can't say that floor $$$\lfloor x \rfloor$$$ is equal to $$$(int)(x)$$$ because for example $$$\lfloor -2.5 \rfloor \neq (int)(-2.5)$$$

Anyway.. I tried to make that function again by myself without using the datatype double

int myfloor(int a, int b) {
    if (a % b == 0) return (a / b);
    bool negative = (a < 0) ^ (b < 0);
    return a / b - negative;
}

int myceil(int a, int b) {
    if (a % b == 0) return (a / b);
    bool positive = !((a < 0) ^ (b < 0));
    return a / b + positive;
}

If there are any better or shorter ways, please write them in the comments. This is the reason for my post (Seeking better solutions)

  • Проголосовать: нравится
  • -24
  • Проголосовать: не нравится

»
2 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Your post has wrong formulas. Please correct them asap.