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?
(Square Root) In the C Programming Language, the sqrt function returns the square root of x.
If we have to find cube root for a perfect cube, then we can just apply binary search directly on the space of [1, N], and return x where x equals to x3 . The (mid != start) and condition, in the while loop, help to return a smaller value in case the loop doesn't find a perfect cube root.
std::cbrt() in C++ The std::cbrt() is an inbuilt function in C++ STL which is used to calculate the cube root of number. It accepts a number as argument and returns the cube root of that number. Syntax: // Returns cube root num (num can be // of type int, double, long double or // long long type.
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
.
The power 1/3
is a special case. In general, non-integral powers of negative numbers are complex. It wouldn't be practical for pow to check for special cases like integer roots, and besides, 1/3
as a double is not exactly 1/3!
I don't know about the visual C++ pow, but my man page says under errors:
EDOM
The argumentx
is negative andy
is not an integral value. This would result in a complex number.
You'll have to use a more specialized cube root function if you want cube roots of negative numbers - or cut corners and take absolute value, then take cube root, then multiply the sign back on.
Note that depending on context, a negative number x
to the 1/3
power is not necessarily the negative cube root you're expecting. It could just as easily be the first complex root, x^(1/3) * e^(pi*i/3)
. This is the convention mathematica uses; it's also reasonable to just say it's undefined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With