Search code examples
pythonalgorithmfloating-pointprecisionnth-root

Precise nth root


I'm looking for Python Nth root function/algorithm but before you post: NO INTEGER ROOT, HELL!
Where could I obtain at least a guide how to program Nth root function that produces precise float/Decimal?
Such function that doesn't return 1 nor 0 for root(125, 1756482845) (1st argument is the number, 2nd is the root depth (or something)).

EDIT: So, you were giving me this solution: n ** (1.0 / exp) which I knew when I asked this question, but it just doesn't work for, for example, exp = 3. You can't express 1/3 in terms of rational numbers, so 125 ** (1/3) gives incorrect result 4.999999.... I was asking for some "smart" algorithm, which gives correct result for such nice numbers and at least 4-decimal-points-accurate result for rational exp. If there isn't such function or algorithm, I will use this (n ** (1/exp)).


Solution

  • I would try the gmpy2 library.

    >>> import gmpy2
    >>> gmpy2.root(125,3)
    mpfr('5.0')
    >>> 
    

    gmpy2 uses the MPFR library to perform correctly rounded floating point operations. The default precision is 53 bits but that can be increased.

    >>> gmpy2.root(1234567890123456789**11, 11)
    mpfr('1.2345678901234568e+18')  # Last digits are incorrect.
    >>> gmpy2.get_context().precision=200
    >>> gmpy2.root(1234567890123456789**11, 11)
    mpfr('1234567890123456789.0',200)
    >>> 
    

    Disclaimer: I maintain gmpy2.