Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the nth root of a value?

Tags:

swift

In Swift, what would the easiest way to find the nth root of a value be?

like image 318
Rory Avatar asked May 13 '15 00:05

Rory


2 Answers

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.

like image 86
nhgrif Avatar answered Oct 18 '22 15:10

nhgrif


    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
like image 20
anakin Avatar answered Oct 18 '22 14:10

anakin