Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ceil and floor equivalent in Python 3 without Math module?

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

like image 576
zooks Avatar asked Sep 14 '15 06:09

zooks


People also ask

How do I get ceil and floor value in Python?

The math. ceil() method rounds a number UP to the nearest integer, if necessary, and returns the result. Tip: To round a number DOWN to the nearest integer, look at the math. floor() method.

How do you implement floor function in Python?

The floor() function: floor() method in Python returns the floor of x i.e., the largest integer not greater than x. Syntax: import math math. floor(x) Parameter: x-numeric expression. Returns: largest integer not greater than x.

How do you write a ceil function in Python?

Description. Python number method ceil() returns ceiling value of x - the smallest integer not less than x.


2 Answers

>>> 3/2 1.5 >>> 3//2 # floor 1 >>> -(-3//2) # ceil 2 
like image 103
bakar Avatar answered Oct 11 '22 03:10

bakar


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.

like image 28
James Barton Avatar answered Oct 11 '22 04:10

James Barton