Reputation: 9351
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
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
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
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