Skip to content Skip to sidebar Skip to footer

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

Solution 1:

>>>3/2
1.5
>>>3//2
1
>>>-(-3//2)
2

Solution 2:

Try

def ceil(n):
    returnint(-1 * n // 1 * -1)

def floor(n):
    returnint(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 ifres== n or n < 0else res+1

def floor(n):
    res = int(n)
    return res ifres== n or n >= 0else res-1

Solution 4:

try it like:

if a%b != 0:
  print(int(a//b + 1))else:
  print(int(a/b))

Post a Comment for "Ceil And Floor Equivalent In Python 3 Without Math Module?"