How to find the nth root of a value?

We know that the Nth root of a number, x, is equivalent of raising x to a power that is the reciprocal of N. Knowing this, we can use the pow function to find the Nth root:

let nthRoot = pow(base, (1/n))

where base and n are floating point variables.


    let nthRoot = pow(base, (1/n)) // will return nan for negative base

This expression is a partial solution, because it will not work for negative base numbers.

Ex. The cubic root to -27 is well defined(-3) by all math laws.

Here is a function that calculates the nth-root properly for negative values, where value is the number which will be rooted by n:

    func nthroot(value: Double, _ n: Double) -> Double {
        var res: Double
        if (value < 0 && abs(n % 2) == 1) {
            res = -pow(-value, 1/n)
        } else {
            res = pow(value, 1/n)
        }
        return res
    }

    nthroot(-27, 3) // returns -3

And the same function using ternary operator:

    func nthroot(value: Double, _ n: Double) -> Double {
        return value < 0 && abs(n % 2) == 1 ? -pow(-value, 1/n) : pow(value, 1/n)
    }

    nthroot(-27, 3) // also returns -3

Tags:

Swift