Search code examples
pythonpython-2.7integer-divisionceil

ceil function with high precision


How do I round up a number to the next integer with a high precision?

Input: var1 = (8193/4096) # var1 = 2.00024414063
Output: 3 # As an integer

>>> var1 = 8193/4096
>>> import math
>>> math.ceil(var1)
2.0
>>> math.ceil(8193/4096)
2.0
>>> import numpy
>>> numpy.ceil(8193/4096)

How can I elegantly do this operation?


Solution

  • In Python 2, this:

    >>> var1 = 8193/4096
    

    doesn't do what you think it does. In Python 2, dividing two integers always returns an integer (truncated) as the result.

    >>> 8193/4096
    2
    

    ...and then calling math.ceil() on 2 returns 2.

    Convert one or both of your values to a floating point value and it will do what you like:

    >>> v = 8193/4096.0
    >>> v
    2.000244140625
    >>> math.ceil(v)
    3.0
    

    Alternatives:

    a) switch to Python 3, where division does behave like you want it to:

    bgporter@zappa:~$ python3
    Python 3.4.0 (default, Apr 11 2014, 13:05:18)
    [GCC 4.8.2] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> 8193/4096
    2.000244140625
    >>>
    

    b) enable Python 3's division on Python 2 like this:

    bgporter@varese ~:python
    Python 2.7.5 (default, Mar  9 2014, 22:15:05)
    [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from __future__ import division
    >>> 8193/4096
    2.000244140625