C - finding cube root of a negative number with pow function
there is. Remember: x^(1/3) = -(-x)^(1/3). So the following should do it:
double cubeRoot(double d) {
if (d < 0.0) {
return -cubeRoot(-d);
}
else {
return pow(d,1.0/3.0);
}
}
Written without compiling, so there may be syntax errors.
Greetings, Jost
As Stephen Canon answered, to correct function to use in this case is cbrt(). If you don't know the exponent beforehand, you can look into the cpow() function.
#include <stdio.h>
#include <math.h>
#include <complex.h>
int main(void)
{
printf("cube root cbrt: %g\n", cbrt(-27.));
printf("cube root pow: %g\n", pow(-27., 1./3.));
double complex a, b, c;
a = -27.;
b = 1. / 3;
c = cpow(a, b);
printf("cube root cpow: (%g, %g), abs: %g\n", creal(c), cimag(c), cabs(c));
return 0;
}
prints
cube root cbrt: -3 cube root pow: -nan cube root cpow: (1.5, 2.59808), abs: 3
Keep in mind the definition of the complex power: cpow(a, b) = cexp(b* clog(a)).
7.12.7.1 The cbrt
functions
Synopsis
#include <math.h>
double cbrt(double x);
float cbrtf(float x);
long double cbrtl(long double x);
Description
The cbrt
functions compute the real cube root of x
.
If you're curious, pow
can't be used to compute cube roots because one-third is not expressible as a floating-point number. You're actually asking pow
to raise -27.0
to a rational power very nearly equal to 1/3; there is no real result that would be appropriate.