Ceil and floor equivalent in Python 3 without Math module?
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
Related videos on Youtube
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, 2022Comments
-
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 almost 9 yearswrong result for 4/2
-
Ffisegydd almost 9 yearsWhy not just use the
math
library? -
zooks almost 9 yearsfor education purposes
-
zooks almost 9 yearsBelieve me, I tried. BTW I used PHP before, now I'm learning Python :)
-
Mark Dickinson almost 9 yearsUse the ceiling division operator,
--0--
! This converts floor division to ceiling division. For example,--0-- 3//2
gives the ceiling of3/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 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 almost 9 years@zooks: More seriously, use the fact that
ceiling(x)
==-floor(-x)
for any real numberx
. -
user202729 over 2 yearsDoes this answer your question? Is there a ceiling equivalent of // operator in Python?
-
-
Mark Dickinson almost 9 yearsThis
floor
definition is broken: it won't work correctly for negative integers. -
soshial over 6 yearsfunny that
>>>math.ceil(4.0000000000000001/2)
is 2, but>>>math.ceil(4.000000000000001/2)
is 3 -
FiddleStix over 2 yearsBut not surprising, when you consider that
4.0000000000000001 == 4.0
isTrue
but4.000000000000001 == 4.0
is False