ihtus
ihtus

Reputation: 2811

C - finding cube root of a negative number with pow function

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?

Upvotes: 12

Views: 17011

Answers (4)

Love Sharma
Love Sharma

Reputation: 1999

Using Newton's Method:

def cubicroot(num):
  flag = 1
  if num < 0:
    flag = -1
    num = num - num - num
  x0 = num / 2.
  x1 = x0 - (((x0 * x0 * x0) - num) / (3. * x0 * x0))
  while(round(x0) != round(x1)):
    x0 = x1
    x1 = x0 - (((x0 * x0 * x0) - num) / (3. * x0 * x0))
  return x1 * flag

print cubicroot(27)

Upvotes: 0

janneb
janneb

Reputation: 37228

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)).

Upvotes: 1

Stephen Canon
Stephen Canon

Reputation: 106247

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.

Upvotes: 20

Jost
Jost

Reputation: 5840

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

Upvotes: 6

Related Questions