In real world cube root for a negative number should exist:
cuberoot(-1)=-1
, that means (-1)*(-1)*(-1)=-1
or
cuberoot(-27)=-3
, that means (-3)*(-3)*(-3)=-27
But when I calculate cube root of a negative number in C using pow
function, I get nan
(not a number)
double cuber;
cuber=pow((-27.),(1./3.));
printf("cuber=%f\n",cuber);
output: cuber=nan
Is there any way to calculate cube root of a negative number in C?
The cube root of a positive number is always positive, and the cube root of a negative number is always negative.
The standard C++ pow() function can handle negative floating point numbers raised to an integer power.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With