Search code examples
pythondivisionminimuminteger-division

How to set minimum value to a division operation in python?


Is there a standard library function which will set a minimum value to a division operation, for example:

min(1, a/b)

This will ensure that min value of operation above will always be 1, never 0.

Such as:

min(1, 1/5)
1

Also, how do I round up a division:

round_up(1/5) = 1

I always get "0" when I divide 1/5, even with ceil function:

math.ceil(1/5)
0

Solution

  • If you want to use floating point division as default, you can do from __future__ import division:

    >>> 1/5
    0
    >>> from __future__ import division
    >>> 1/5
    0.2
    >>> math.ceil(1/5)
    1.0
    

    If you need the result to be of integer type, e.g. for indexing, you can use

    int(math.ceil(1/5))