Ceil and floor equivalent in Python 3 without Math module?

36,408

Solution 1

>>> 3/2
1.5
>>> 3//2 # floor
1
>>> -(-3//2) # ceil
2

Solution 2

Try

def ceil(n):
    return int(-1 * n // 1 * -1)

def floor(n):
    return int(n // 1)

I used int() to make the values integer. As ceiling and floor are a type of rounding, I thought integer is the appropriate type to return.

The integer division //, goes to the next whole number to the left on the number line. Therefore by using -1, I switch the direction around to get the ceiling, then use another * -1 to return to the original sign. The math is done from left to right.

Solution 3

Try:

def ceil(n):
    res = int(n)
    return res if res == n or n < 0 else res+1

def floor(n):
    res = int(n)
    return res if res == n or n >= 0 else res-1
Share:
36,408

Related videos on Youtube

zooks
Author by

zooks

PHP, MySQL, Apache, LAMP, LEMP, Python. CMS: October CMS, Wordpress. Frameworks: Laravel, Django (Python). HTML5, CSS/Sass/SCSS, JavaScript/jQuery/Vue.js/React.js.

Updated on February 24, 2022

Comments

  • zooks
    zooks over 2 years

    I need to ceil and floor 3/2 result (1.5) without using import math.

    math.floor(3/2) => 3//2 math.ceil(3/2) => ?

    OK, here is the problem: to sum all numbers 15 + 45 + 15 + 45 + 15 ... with N items.

    sum = (n//2) * 5 + int(n/2) * 15

    • zooks
      zooks almost 9 years
      wrong result for 4/2
    • Ffisegydd
      Ffisegydd almost 9 years
      Why not just use the math library?
    • zooks
      zooks almost 9 years
      for education purposes
    • zooks
      zooks almost 9 years
      Believe me, I tried. BTW I used PHP before, now I'm learning Python :)
    • Mark Dickinson
      Mark Dickinson almost 9 years
      Use the ceiling division operator, --0--! This converts floor division to ceiling division. For example, --0-- 3//2 gives the ceiling of 3/2. Try it if you don't believe me! (Okay, so you could spell it without the leading --, but it looks better with it.)
    • Mark Dickinson
      Mark Dickinson almost 9 years
      @Ffisegydd: There's at least one good reason to avoid the math library here, which is that by going via floating-point you can lose precision (and get the wrong answer as a result).
    • Mark Dickinson
      Mark Dickinson almost 9 years
      @zooks: More seriously, use the fact that ceiling(x) == -floor(-x) for any real number x.
    • user202729
      user202729 over 2 years
  • Mark Dickinson
    Mark Dickinson almost 9 years
    This floor definition is broken: it won't work correctly for negative integers.
  • soshial
    soshial over 6 years
    funny that >>>math.ceil(4.0000000000000001/2) is 2, but >>>math.ceil(4.000000000000001/2) is 3
  • FiddleStix
    FiddleStix over 2 years
    But not surprising, when you consider that 4.0000000000000001 == 4.0 is True but 4.000000000000001 == 4.0 is False