Search code examples
pythonpython-3.xmathfloor

Floor of very large floats in python


As Python has no limit over integers but has some limit over its floats. How do I go about calculating floor of very large floats?

I am trying to calculate floor(A*B), where A is a small irrational number, possibly sqrt(2), e, sqrt(5) etc and B is a very large number in range 10^1000.


Solution

  • You can use decimal module:

    >>> from decimal import Decimal
    >>> from math import floor, sqrt
    >>> 
    >>> d1 = Decimal(sqrt(2))
    >>> d2 = Decimal(10**1000)
    >>> 
    >>> result = d1 * d2
    >>> floor(result)
    

    You can also set the precision for the decimal using getcontext().prec in order to get more precise result.

    >>> from decimal import *
    >>> getcontext().prec = 100
    >>> d1 = Decimal(2).sqrt()
    >>> d1
    Decimal('1.414213562373095048801688724209698078569671875376948073176679737990732478462107038850387534327641573')