# Calculating the Cube root.

We all know that we can easily calculate the cube root using pow() func. But the question is how to do it without using this func. or any other such function?

If you really don’t want to use any <math.h> function, the easiest is binary search.

``````double CubeRoot(double x) {
double left = 0, right = max(1.0, x);  // note that the root for x in [0, 1[ is larger than x.
double precision = 0.001;
while (left + precision < right) {
double r = (left + right) / 2;
if (r*r*r > x) {
right = r;
} else {
left = r;
}
}
return left;
}
``````

There are more advanced methods like the Newton-Raphson.

7 Likes

You can do it using binary search. let x be the number you have to find the cube root of.
then here is the outline of what you will code :

double hi = max(x, 1), lo = 0, mid;

for (int i = 0; i < 200; ++i) {

mid = (lo + hi)/2.0;

if (mid * mid * mid < x) lo = mid;

else hi = mid;

}

200 is randomly chosen you can choose any big enough number as the value of mid keeps getting closer to x^(1/3) after each iteration.

2 Likes

much better answer than mine Note that the nth root for numbers between 0 and 1 is actually larger than the number, e.g. cubic root of 0.5 is 0.8122…
So hi should be max(1, x).

2 Likes

Yeah, I saw that in your answer 1 Like