Joseph
Joseph

Reputation: 9351

Calculate nth root?

Is there a way to calculate the nth root of a double in objective-c?

I couldn't seem to find an appropriate function.

Upvotes: 7

Views: 5163

Answers (4)

Albert Renshaw
Albert Renshaw

Reputation: 17902

I have this in my #Math.h macros file which I import when needed

#define rootf(__radicand, __index) (powf(((float)__radicand),(1.0f/((float)__index))))

So cubed root of 20 would be rootf(20,3)

Upvotes: 0

fceruti
fceruti

Reputation: 2445

You have to use the pow function:

pow(d, 1.0/n)

enter image description here

Upvotes: 15

flo von der uni
flo von der uni

Reputation: 748

For odd numbered roots (e.g. cubic) and negative numbers, the result of the root is well defined and negative, but just using pow(value, 1.0/n) won’t work (you get back ’NaN’ - not a number).

So, use this instead:

int f = (value < 0 && (n % 2 == 1)) ? -1 : 1;
root = pow(value * f, 1.0/n) * f

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324690

Mathematically, the n-th root of x is x to the power of 1/n.

I have no idea what the syntax of objective-c would be, but basically you just want to use the power function with 1/n as the exponent.

Upvotes: 3

Related Questions