Search code examples
pythonmathdecimalnth-root

calculating n-th roots using Python 3's decimal module


Is there a built-in way to calculate the correctly rounded n-th root of a Python 3 decimal object?


Solution

  • According to the documentation, there is a function power(x,y) :

    With two arguments, compute x**y. If x is negative then y must be integral. The result will be inexact unless y is integral and the result is finite and can be expressed exactly in ‘precision’ digits. The result should always be correctly rounded, using the rounding mode of the current thread’s context

    This implies that power(x, 1.0/n) should give you what you want.

    You can also take the nth root with

    nthRoot = Decimal(x) ** (Decimal(1.0) / Decimal(n) )
    

    Not sure if you consider either of these "built in" as you have to compute the reciprocal of n explicitly to get the nth root.