Ceil and floor equivalent in Python 3 without Math module?
How can you implement ceil and floor functions in Python 3 without using the Math module? Understanding this helps when you need rounding operations but want to avoid external dependencies or practice logic-based solutions.
In Python, the math module provides convenient functions like math.ceil() and math.floor() to round numbers up or down. But what if you want to achieve the same behavior without using the math module? Luckily, Python has built-in operators and functions that make this possible.
Approaches Without math Module:
Using int() for floor behavior
The int() function truncates the decimal part towards zero. For positive numbers, this works the same as floor:
num = 5.7
floor_val = int(num) # Output: 5 However, for negative numbers, truncation differs from floor:
num = -5.7
floor_val = int(num) # Output: -5 (but floor should be -6) To fix this, you can adjust by subtracting 1 if the number is negative and not already an integer.
Using division with // (floor division operator)
The // operator in Python always performs floor division:
num = -5.7
floor_val = num // 1 # Output: -6Implementing ceil manually
You can combine truncation and a check:
num = 5.2
ceil_val = int(num) if num == int(num) else int(num) + 1
# Output: 6 For negatives, int() already moves towards zero, so you don’t need to add 1 unless the number is positive with a fraction.
Key Points:
- Use // 1 for floor values since it works correctly for both positive and negative numbers.
- For ceil, use integer truncation plus a conditional check.
- These methods avoid importing math, yet give you the same results.