Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

math

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?

like image 835
ihtus Avatar asked Dec 13 '11 16:12

ihtus


People also ask

Can you find cube root of negative number?

The cube root of a positive number is always positive, and the cube root of a negative number is always negative.

Does POW work with negative numbers?

The standard C++ pow() function can handle negative floating point numbers raised to an integer power.


2 Answers

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.

like image 57
Stephen Canon Avatar answered Sep 28 '22 20:09

Stephen Canon


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

like image 25
Jost Avatar answered Sep 28 '22 19:09

Jost