How do you round UP a number? - python

How does one round a number UP in Python?
I tried round(number) but it rounds the number down. Example:
round(2.3) = 2.0
and not 3, as I would like.
The I tried int(number + .5) but it round the number down again! Example:
int(2.3 + .5) = 2

The math.ceil (ceiling) function returns the smallest integer higher or equal to x.
For Python 3:
import math
print(math.ceil(4.2))
For Python 2:
import math
print(int(math.ceil(4.2)))

I know this answer is for a question from a while back, but if you don't want to import math and you just want to round up, this works for me.
>>> int(21 / 5)
4
>>> int(21 / 5) + (21 % 5 > 0)
5
The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.

If working with integers, one way of rounding up is to take advantage of the fact that // rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed.
rounded_up = -(-numerator // denominator)
For example:
>>> print(-(-101 // 5))
21

Interesting Python 2.x issue to keep in mind:
>>> import math
>>> math.ceil(4500/1000)
4.0
>>> math.ceil(4500/1000.0)
5.0
The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.
In javascript, the exact same code produces a different result:
console.log(Math.ceil(4500/1000));
5

You might also like numpy:
>>> import numpy as np
>>> np.ceil(2.3)
3.0
I'm not saying it's better than math, but if you were already using numpy for other purposes, you can keep your code consistent.
Anyway, just a detail I came across. I use numpy a lot and was surprised it didn't get mentioned, but of course the accepted answer works perfectly fine.

Use math.ceil to round up:
>>> import math
>>> math.ceil(5.4)
6.0
NOTE: The input should be float.
If you need an integer, call int to convert it:
>>> int(math.ceil(5.4))
6
BTW, use math.floor to round down and round to round to nearest integer.
>>> math.floor(4.4), math.floor(4.5), math.floor(5.4), math.floor(5.5)
(4.0, 4.0, 5.0, 5.0)
>>> round(4.4), round(4.5), round(5.4), round(5.5)
(4.0, 5.0, 5.0, 6.0)
>>> math.ceil(4.4), math.ceil(4.5), math.ceil(5.4), math.ceil(5.5)
(5.0, 5.0, 6.0, 6.0)

I am surprised nobody suggested
(numerator + denominator - 1) // denominator
for integer division with rounding up. Used to be the common way for C/C++/CUDA (cf. divup)

The syntax may not be as pythonic as one might like, but it is a powerful library.
https://docs.python.org/2/library/decimal.html
from decimal import *
print(int(Decimal(2.3).quantize(Decimal('1.'), rounding=ROUND_UP)))

For those who want to round up a / b and get integer:
Another variant using integer division is
def int_ceil(a, b):
return (a - 1) // b + 1
>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5
Note: a and b must be non-negative integers

Here is a way using modulo and bool
n = 2.3
int(n) + bool(n%1)
Output:
3

Try this:
a = 211.0
print(int(a) + ((int(a) - a) != 0))

Be shure rounded value should be float
a = 8
b = 21
print math.ceil(a / b)
>>> 0
but
print math.ceil(float(a) / b)
>>> 1.0

The above answers are correct, however, importing the math module just for this one function usually feels like a bit of an overkill for me. Luckily, there is another way to do it:
g = 7/5
g = int(g) + (not g.is_integer())
True and False are interpreted as 1 and 0 in a statement involving numbers in python. g.is_interger() basically translates to g.has_no_decimal() or g == int(g). So the last statement in English reads round g down and add one if g has decimal.

In case anyone is looking to round up to a specific decimal place:
import math
def round_up(n, decimals=0):
multiplier = 10 ** decimals
return math.ceil(n * multiplier) / multiplier

Without importing math // using basic envionment:
a) method / class method
def ceil(fl):
return int(fl) + (1 if fl-int(fl) else 0)
def ceil(self, fl):
return int(fl) + (1 if fl-int(fl) else 0)
b) lambda:
ceil = lambda fl:int(fl)+(1 if fl-int(fl) else 0)

>>> def roundup(number):
... return round(number+.5)
>>> roundup(2.3)
3
>>> roundup(19.00000000001)
20
This function requires no modules.

x * -1 // 1 * -1
Confusing but it works: For x=7.1, you get 8.0. For x = -1.1, you get -1.0
No need to import a module.

For those who doesn't want to use import.
For a given list or any number:
x = [2, 2.1, 2.5, 3, 3.1, 3.5, 2.499,2.4999999999, 3.4999999,3.99999999999]
You must first evaluate if the number is equal to its integer, which always rounds down. If the result is True, you return the number, if is not, return the integer(number) + 1.
w = lambda x: x if x == int(x) else int(x)+1
[w(i) for i in z]
>>> [2, 3, 3, 3, 4, 4, 3, 3, 4, 4]
Math logic:
If the number has decimal part: round_up - round_down == 1, always.
If the number doens't have decimal part: round_up - round_down == 0.
So:
round_up == x + round_down
With:
x == 1 if number != round_down
x == 0 if number == round_down
You are cutting the number in 2 parts, the integer and decimal. If decimal isn't 0, you add 1.
PS:I explained this in details since some comments above asked for that and I'm still noob here, so I can't comment.

If you don't want to import anything, you can always write your own simple function as:
def RoundUP(num):
if num== int(num):
return num
return int(num + 1)

To do it without any import:
>>> round_up = lambda num: int(num + 1) if int(num) != num else int(num)
>>> round_up(2.0)
2
>>> round_up(2.1)
3

I know this is from quite a while back, but I found a quite interesting answer, so here goes:
-round(-x-0.5)
This fixes the edges cases and works for both positive and negative numbers, and doesn't require any function import
Cheers

I'm surprised I haven't seen this answer yet round(x + 0.4999), so I'm going to put it down. Note that this works with any Python version. Changes made to the Python rounding scheme has made things difficult. See this post.
Without importing, I use:
def roundUp(num):
return round(num + 0.49)
testCases = list(x*0.1 for x in range(0, 50))
print(testCases)
for test in testCases:
print("{:5.2f} -> {:5.2f}".format(test, roundUp(test)))
Why this works
From the docs
For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done toward the even choice
Therefore 2.5 gets rounded to 2 and 3.5 gets rounded to 4. If this was not the case then rounding up could be done by adding 0.5, but we want to avoid getting to the halfway point. So, if you add 0.4999 you will get close, but with enough margin to be rounded to what you would normally expect. Of course, this will fail if the x + 0.4999 is equal to [n].5000, but that is unlikely.

You could use round like this:
cost_per_person = round(150 / 2, 2)

You can use floor devision and add 1 to it.
2.3 // 2 + 1

when you operate 4500/1000 in python, result will be 4, because for default python asume as integer the result, logically:
4500/1000 = 4.5 --> int(4.5) = 4
and ceil of 4 obviouslly is 4
using 4500/1000.0 the result will be 4.5 and ceil of 4.5 --> 5
Using javascript you will recieve 4.5 as result of 4500/1000, because javascript asume only the result as "numeric type" and return a result directly as float
Good Luck!!

I think you are confusing the working mechanisms between int() and round().
int() always truncates the decimal numbers if a floating number is given; whereas round(), in case of 2.5 where 2 and 3 are both within equal distance from 2.5, Python returns whichever that is more away from the 0 point.
round(2.5) = 3
int(2.5) = 2

My share
I have tested print(-(-101 // 5)) = 21 given example above.
Now for rounding up:
101 * 19% = 19.19
I can not use ** so I spread the multiply to division:
(-(-101 //(1/0.19))) = 20

I'm basically a beginner at Python, but if you're just trying to round up instead of down why not do:
round(integer) + 1

Related

Comparing two variables upto x decimal places

Let a = 1.11114
b = 1.11118
When I compare these two variables using the code below
if b <= a
I want the comparison to be done only up to 4 decimal places, such that a = b.
Can anyone help me with an efficient code?
Thank you!
To avoid rounding, you can multiply the number by power of 10 to cast to integer up to the decimal place you want to consider (to truncate the decimal part), and then divide by the same power to obtain the truncated float:
n = 4 # number of decimal digits you want to consider
a_truncated = int(a * 10**n)/10**n
See also Python setting Decimal Place range without rounding?
Possible duplicate of Truncate to three decimals in Python
Extract x digits with the power of 10^x and then divide by the same:
>>> import math
>>> def truncate(number, digits) -> float:
... stepper = 10.0 ** digits
... return math.trunc(stepper * number) / stepper
>>> a
1.11114
>>> b
1.11118
>>> truncate(a,4) == truncate(b,4)
True
Solution by #Erwin Mayer
You can look at whether their differences is close to 0 with an absolute tolerance of 1e-4 with math.isclose:
>>> import math
>>> math.isclose(a - b, 0, abs_tol=1e-4)
True
Use round() in-built function -
a = round(a,4) # 4 is no. of digits you want
b = round(b,4)
if a >= b :
... # Do stuff

Python3 division: return int when there's no remainder and a float when there is a remainder?

In python3, integer division works differently than in python 2.7.3. Is there a way to ensure that a number that doesn't have a remainder after division is returned as an int, while a number that does have a remainder after division is returned as a float?
I'd like to be able to check:
if (instanceof(x/n, int)):
# do something
The following occurs in python3:
>>> 4 / 2
2.0
>>> 5 / 2
2.5
Is there some way to make division act like this?
>>> 4 / 2
2
>>> 5 / 2
2.5
You'd have to implement it yourself. Obvious approach would be:
def divspecial(n, d):
q, r = divmod(n, d) # Get quotient and remainder of division (both int)
if not r:
return q # If no remainder, return quotient
return n / d # Otherwise, compute float result as accurately as possible
Of course, if you're just trying to check if division would be exact or not, don't use nonsense like the function above to check:
if isinstance(divspecial(x, n), int):
Just test the remainder directly:
if x % n == 0: # If remainder is 0, division was exact
I don't think there is a way to make it automatic, but you could always do a quick check afterwards to convert it:
r = 4/2
if r%1==0:
r=int(r)

How to check if a float value is a whole number

I am trying to find the largest cube root that is a whole number, that is less than 12,000.
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?
To check if a float value is a whole number, use the float.is_integer() method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float type in Python 2.6.
Take into account that in Python 2, 1/3 is 0 (floor division for integer operands!), and that floating point arithmetic can be imprecise (a float is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float() to find your number. Like rounding down the cube root of 12000:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose() function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
We can use the modulo (%) operator. This tells us how many remainders we have when we divide x by y - expresses as x % y. Every whole number must divide by 1, so if there is a remainder, it must not be a whole number.
This function will return a boolean, True or False, depending on whether n is a whole number.
def is_whole(n):
return n % 1 == 0
You could use this:
if k == int(k):
print(str(k) + " is a whole number!")
You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:
r = int(12000**(1/3.0))
print r*r*r # 10648
You can use a modulo operation for that.
if (n ** (1.0/3)) % 1 != 0:
print("We have a decimal number here!")
How about
if x%1==0:
print "is integer"
Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.
for i in range(20, 30):
print("Trying {0}".format(i))
if i ** 3 > 12000:
print("Maximum integral cube root less than 12000: {0}".format(i - 1))
break
The above answers work for many cases but they miss some. Consider the following:
fl = sum([0.1]*10) # this is 0.9999999999999999, but we want to say it IS an int
Using this as a benchmark, some of the other suggestions don't get the behavior we might want:
fl.is_integer() # False
fl % 1 == 0 # False
Instead try:
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
def is_integer(fl):
return isclose(fl, round(fl))
now we get:
is_integer(fl) # True
isclose comes with Python 3.5+, and for other Python's you can use this mostly equivalent definition (as mentioned in the corresponding PEP)
Just a side info, is_integer is doing internally:
import math
isInteger = (math.floor(x) == x)
Not exactly in python, but the cpython implementation is implemented as mentioned above.
All the answers are good but a sure fire method would be
def whole (n):
return (n*10)%10==0
The function returns True if it's a whole number else False....I know I'm a bit late but here's one of the interesting methods which I made...
Edit: as stated by the comment below, a cheaper equivalent test would be:
def whole(n):
return n%1==0
You can use something like:
num = 1.9899
bool(int(num)-num)
#returns True
if it is True, It means it holds some value, hence not a whole number. Else
num = 1.0
bool(int(num)-num)
# returns False
>>> def is_near_integer(n, precision=8, get_integer=False):
... if get_integer:
... return int(round(n, precision))
... else:
... return round(n) == round(n, precision)
...
>>> print(is_near_integer(10648 ** (1.0/3)))
True
>>> print(is_near_integer(10648 ** (1.0/3), get_integer=True))
22
>>> for i in [4.9, 5.1, 4.99, 5.01, 4.999, 5.001, 4.9999, 5.0001, 4.99999, 5.000
01, 4.999999, 5.000001]:
... print(i, is_near_integer(i, 4))
...
4.9 False
5.1 False
4.99 False
5.01 False
4.999 False
5.001 False
4.9999 False
5.0001 False
4.99999 True
5.00001 True
4.999999 True
5.000001 True
>>>
This problem has been solved, but I would like to propose an additional mathematical-based solution for funcies.
The benefit of this approach is that it calculates the whole number part of your number, which may be beneficial depending on your general task.
Algorithm:
Decompose whole number part of your number its a sum of its decimals (e.g., 327=3*100+2*10+7*1)
take difference between calculated whole number and number itself
decide whether difference is close enough to be considered an integer.
from math import ceil, log, isclose
def is_whole(x: float) -> bool:
n_digits = ceil(log(x,10)) # number of digits of decimals at or above ones
digits = [(n//(10**i))%10 for i in range(n_digits)] # parse digits of `x` at or above ones decimal
whole = 0 # will equal the whole number part of `x`
for i in range(n_digits):
decimal = 10**i
digit = digits[i]
whole += digit*decimal
diff = whole - x
return isclose(diff, 0.0)
NOTE: the idea of parsing digits of a number was realized from here
Try using:
int(val) == val
It will give lot more precision than any other methods.
You can use the round function to compute the value.
Yes in python as many have pointed when we compute the value of a cube root, it will give you an output with a little bit of error. To check if the value is a whole number you can use the following function:
def cube_integer(n):
if round(n**(1.0/3.0))**3 == n:
return True
return False
But remember that int(n) is equivalent to math.floor and because of this if you find the int(41063625**(1.0/3.0)) you will get 344 instead of 345.
So please be careful when using int withe cube roots.

Basic python arithmetic - division

I have two variables : count, which is a number of my filtered objects, and constant value per_page. I want to divide count by per_page and get integer value but I no matter what I try - I'm getting 0 or 0.0 :
>>> count = friends.count()
>>> print count
1
>>> per_page = 2
>>> print per_page
2
>>> pages = math.ceil(count/per_pages)
>>> print pages
0.0
>>> pages = float(count/per_pages)
>>> print pages
0.0
What am I doing wrong, and why math.ceil gives float number instead of int ?
Python does integer division when both operands are integers, meaning that 1 / 2 is basically "how many times does 2 go into 1", which is of course 0 times. To do what you want, convert one operand to a float: 1 / float(2) == 0.5, as you're expecting. And, of course, math.ceil(1 / float(2)) will yield 1, as you expect.
(I think this division behavior changes in Python 3.)
Integer division is the default of the / operator in Python < 3.0. This has behaviour that seems a little weird. It returns the dividend without a remainder.
>>> 10 / 3
3
If you're running Python 2.6+, try:
from __future__ import division
>>> 10 / 3
3.3333333333333335
If you're running a lower version of Python than this, you will need to convert at least one of the numerator or denominator to a float:
>>> 10 / float(3)
3.3333333333333335
Also, math.ceil always returns a float...
>>> import math
>>> help(math.ceil)
ceil(...)
ceil(x)
Return the ceiling of x as a float.
This is the smallest integral value >= x.
From Python documentation (math module):
math.ceil(x)
Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
They're integers, so count/per_pages is zero before the functions ever get to do anything beyond that. I'm not a Python programmer really but I know that (count * 1.0) / pages will do what you want. There's probably a right way to do that however.
edit — yes see #mipadi's answer and float(x)
its because how you have it set up is performing the operation and then converting it to a float try
count = friends.count()
print count
per_page = float(2)
print per_page
pages = math.ceil(count/per_pages)
print pages
pages = count/per_pages
By converting either count or per_page to a float all of its future operations should be able to do divisions and end up with non whole numbers
>>> 10 / float(3)
3.3333333333333335
>>> #Or
>>> 10 / 3.0
3.3333333333333335
>>> #Python make any decimal number to float
>>> a = 3
>>> type(a)
<type 'int'>
>>> b = 3.0
>>> type(b)
<type 'float'>
>>>
The best solution maybe is to use from __future__ import division

getting Ceil() of Decimal in python?

Is there a way to get the ceil of a high precision Decimal in python?
>>> import decimal;
>>> decimal.Decimal(800000000000000000001)/100000000000000000000
Decimal('8.00000000000000000001')
>>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000)
8.0
math rounds the value and returns non precise value
The most direct way to take the ceiling of a Decimal instance x is to use x.to_integral_exact(rounding=ROUND_CEILING). There's no need to mess with the context here. Note that this sets the Inexact and Rounded flags where appropriate; if you don't want the flags touched, use x.to_integral_value(rounding=ROUND_CEILING) instead. Example:
>>> from decimal import Decimal, ROUND_CEILING
>>> x = Decimal('-123.456')
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')
Unlike most of the Decimal methods, the to_integral_exact and to_integral_value methods aren't affected by the precision of the current context, so you don't have to worry about changing precision:
>>> from decimal import getcontext
>>> getcontext().prec = 2
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')
By the way, in Python 3.x, math.ceil works exactly as you want it to, except that it returns an int rather than a Decimal instance. That works because math.ceil is overloadable for custom types in Python 3. In Python 2, math.ceil simply converts the Decimal instance to a float first, potentially losing information in the process, so you can end up with incorrect results.
x = decimal.Decimal('8.00000000000000000000001')
with decimal.localcontext() as ctx:
ctx.prec=100000000000000000
ctx.rounding=decimal.ROUND_CEILING
y = x.to_integral_exact()
You can do this using the precision and rounding mode option of the Context constructor.
ctx = decimal.Context(prec=1, rounding=decimal.ROUND_CEILING)
ctx.divide(decimal.Decimal(800000000000000000001), decimal.Decimal(100000000000000000000))
EDIT: You should consider changing the accepted answer.. Although the prec can be increased as needed, to_integral_exact is a simpler solution.
>>> decimal.Context(rounding=decimal.ROUND_CEILING).quantize(
... decimal.Decimal(800000000000000000001)/100000000000000000000, 0)
Decimal('9')
def decimal_ceil(x):
int_x = int(x)
if x - int_x == 0:
return int_x
return int_x + 1
Just use potency to make this.
import math
def lo_ceil(num, potency=0): # Use 0 for multiples of 1, 1 for multiples of 10, 2 for 100 ...
n = num / (10.0 ** potency)
c = math.ceil(n)
return c * (10.0 ** potency)
lo_ceil(8.0000001, 1) # return 10

Categories