Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding a math calculation up, without math.ceil()?

I'm working on a system which doesn't have the math module available. All "Math" functions installed (math.ceil(), math.round(), etc all produce errors).

I have even tried using import math which yields:

<type 'ImportError'>
__import__ not found

Current issue that is stumping me: How can I make a math calculation round up to a whole number without math.ceil?

like image 841
EdwardB Avatar asked Jun 15 '26 16:06

EdwardB


2 Answers

If x is a float number that you want to round up to an integer, and you want an integer type result, you could use

rounded_up_x = int(-(-x // 1))

This works because integer division by one rounds down, but using the negative sign before and after doing the division rounds the opposite direction. The int here converts the float result to an integer. Remove that int if you want a floating point value that equals an integer, which is what some programming languages do.

Hat-tip to @D.LaRocque for pointing out that Python's ceil() function returns an integer type.

like image 194
Rory Daulton Avatar answered Jun 18 '26 00:06

Rory Daulton


in Python 3, we have object.__ceil__() that is even called by math.ceil internally,

num = 12.4 / 3.3
print(num)
3.757575757575758
num.__ceil__()
4

Or one can always negate the result of a negated number's floor division (and create a new int object unless a float would do),

int(-(-12.4 // 3.3))
4
like image 37
Nikhil Saxena Avatar answered Jun 17 '26 23:06

Nikhil Saxena