Strange things happen when i try to find the cube root of a number.
The following code returns me undefined. In cmd : -1.#IND
cout<<pow(( double )(20.0*(-3.2) + 30.0),( double )1/3)
While this one works perfectly fine. In cmd : 4.93242414866094
cout<<pow(( double )(20.0*4.5 + 30.0),( double )1/3)
From mathematical way it must work since we can have the cube root from a negative number. Pow is from Visual C++ 2010 math.h library. Any ideas?
I was looking for cubit root and found this thread and it occurs to me that the following code might work:
C++11 has the
cbrt
function (see for example http://en.cppreference.com/w/cpp/numeric/math/cbrt) so you can write something likeI do not have access to the C++ standard so I do not know how the negative argument is handled... a test on ideone http://ideone.com/bFlXYs seems to confirm that C++ (gcc-4.8.1) extends the cube root with this rule
cbrt(x)=-cbrt(-x)
whenx<0
; for this extension you can see http://mathworld.wolfram.com/CubeRoot.htmlDon't cast to
double
by using(double)
, use a double numeric constant instead:Should do the trick!
Also: don't include
<math.h>
in C++ projects, but use<cmath>
instead.Alternatively, use
pow
from the<complex>
header for the reasons stated by buddhabrotbecause the 1/3 will always return 0 as it will be considered as integer... try with 1.0/3.0... it is what i think but try and implement... and do not forget to declare variables containing 1.0 and 3.0 as double...
If you ever have no math library you can use this way to compute the cubic root:
cubic root
It is derives from the
sqrt
algorithm below. The idea is thatb
andx / b / b
bigger and smaller from the cubic root ofx
. So, the average of both lies closer to the cubic root ofx
.Square Root And Cubic Root (in Python)
In contrast to the square root,
last_b_1
andlast_b_2
are required in the cubic root because b flickers. You can modify these algorithms to compute the fourth root, fifth root and so on.Thanks to my math teacher Herr Brenner in 11th grade who told me this algorithm for
sqrt
.Performance
I tested it on an Arduino with 16mhz clock frequency:
0.3525ms
for yourPow0.3853ms
for nth-root2.3426ms
for curtGuess you gotta take the negative out and put it in afterwards. You can have a wrapper do this for you if you really want to.