Finding Cube Root in C++

How can I obtain the cube root in C++?

sqrt stands for "square root", and "square root" means raising to the power of 1/2. There is no such thing as "square root with root 2", or "square root with root 3". For other roots, you change the first word; in your case, you are seeking how to perform cube rooting.

Before C++11, there is no specific function for this, but you can go back to first principles:

  • Square root: std::pow(n, 1/2.) (or std::sqrt(n))
  • Cube root: std::pow(n, 1/3.) (or std::cbrt(n) since C++11)
  • Fourth root: std::pow(n, 1/4.)
  • etc.

If you're expecting to pass negative values for n, avoid the std::pow solution — it doesn't support negative inputs with fractional exponents, and this is why std::cbrt was added:

std::cout << std::pow(-8, 1/3.) << '\n';  // Output: -nan
std::cout << std::cbrt(-8) << '\n'; // Output: -2

N.B. That . is really important, because otherwise 1/3 uses integer division and results in 0.

C - Finding Cube root of a number

The problem is that cbrt accepts and returns a float or double value, which means that cbrt(n) will automatically convert n to a float/double before passing it to the function. The function will return a float/double but you are not storing it anywhere to force a conversion back to an int, you are directly passing it to printf specifying %d so the value is interpreted as an int even though it is actually a float/double.

A simple cast would be enough: (int)cbrt(n), or you could use %f or %g specifier and print it as its real type.

Also storing in a temporary variable would lead to the same conversion behavior:

int v = cbrt(n);
printf("%d\n", v);

finding cube root in C++?

pow(x, y) from <cmath> does NOT work if x is negative and y is non-integral.

This is a limitation of std::pow, as documented in the C standard and on cppreference:

Error handling

  • Errors are reported as specified in math_errhandling
  • If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur.
  • If base is zero and exp is zero, a domain error may occur.
  • If base is zero and exp is negative, a domain error or a pole error may occur.

There are a couple ways around this limitation:

  • Cube-rooting is the same as taking something to the 1/3 power, so you could do std::pow(x, 1/3.).

  • In C++11, you can use std::cbrt. C++11 introduced both square-root and cube-root functions, but no generic n-th root function that overcomes the limitations of std::pow.

Find cube root in C

you can use cbrt() function in math.h file

#include<math.h>

//cbrt(x) to get cube root of x :)

printf("cube root is %f \n",cbrt(x));

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

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.

Cube root of a number, C++

The problem as you're stating it can be solved trivially (with real numbers the cubic root of -x is the opposite of the cubic root of x):

double cuberoot(double x) {
if (x < 0) {
return -pow(-x, 1.0/3.0);
} else if (x > 0) {
return pow(x, 1.0/3.0);
} else {
return 0;
}
}

If the input is instead in general complex z and you're looking for the "most real" (principal) cubic root the same reasoning can be applied using complex pow version to either z or -z depending on the sign of the real part:

std::complex<double> cuberoot(std::complex<double> z) {
if (z.real() < 0) {
return -pow(-z, 1.0/3.0);
} else {
return pow(z, 1.0/3.0);
}
}

Integer cube root

The book "Hacker's Delight" has algorithms for this and many other problems. The code is online here. EDIT: That code doesn't work properly with 64-bit ints, and the instructions in the book on how to fix it for 64-bit are somewhat confusing. A proper 64-bit implementation (including test case) is online here.

I doubt that your squareroot function works "correctly" - it should be ulong a for the argument, not n :) (but the same approach would work using cbrt instead of sqrt, although not all C math libraries have cube root functions).

Find Cube root of a number Using System.Math.Pow() method in C#

This is a standard trap in the { curly brace languages }, C# included, a division with integral operands is performed as an integer division, not a floating point division. It always yields an integer result, 1 / 3 produces 0. Raising any number to the power of 0 produces 1.0

You force a floating point division by converting one of the operands to double. Like 1.0 / 3 or (double)integerVariable / 3.

Similar problem with multiplication, but usually less of a trap, integral operands produce an integral result that risks overflow. This otherwise reflects the way the processor works, it has distinct instructions for these operations, IMUL vs FMUL and IDIV vs FDIV. The latter one being rather famous for a bug in the Pentium processor :)

Cubic Root Algorithm in O(n) and O(log n) time

For O(n) you can just iterate from 0 to n, checking if the number is the cubic root you're looking for. (This only works with integers)

int cubic(int n){
for(int i=0;i<=n;i++)
if(i*i*i==n)
return i;
return -1; // cubic root doesn't exist.
}

For O(logn) you can do a binary search from 0 to n:

double error=0.00000001;
double cubic(double n){
double l=0, r=n, m=(r+l)/2;
while (abs(n-m*m*m)>error){ // if difference between m^3 and n is not satisfactory
m=(r+l)/2;
if(m*m*m<n) // if m^3 < n, then the root is definitely greater then m, so we move the left border
l=m;
else // otherwise, move the right border
r=m;
}
return m;
}


Related Topics



Leave a reply



Submit