Search code examples
pythonmath

Is there a root function in python?


I want a thing that you can import two numbers and it will calculate the root of the number.

like I put (4, 2) and it output 2 or (27, 3) or ant combination.

I already tried: math.sqrt, but this is only for square root.


Solution

  • Mathematically, n-th root of x is equivalent to x to the power of 1/n. So:

    def nth_root(x, n):
        return x ** (1 / n)
    
    print(nth_root(4, 2))
    # => 2.0
    
    print(nth_root(27, 3))
    # => 3.0