Cubic root of the negative number on python
You could use:
-math.pow(3, float(1)/3)
Or more generally:
if x > 0:
return math.pow(x, float(1)/3)
elif x < 0:
return -math.pow(abs(x), float(1)/3)
else:
return 0
Real cube root of a negative number
Sounds like you just need to define your own Math.cbrt()
function.
That will turn performing the operation from something inelegant and cumbersome to something clean, expressive, and easy to apply:
Math.cbrt <- function(x) {
sign(x) * abs(x)^(1/3)
}
x <- c(-1, -8, -27, -64)
Math.cbrt(x)
# [1] -1 -2 -3 -4
How to get the real cube root of a negative number in Python3?
In the second case actually the cube root is getting evaluated first then the minus sign is getting applied, hence the real root.
That is -1636.281**(1/3)
becomes -(1636.281**(1/3))
. And you can use a similar logic to get the real cubic roots as well.
But actually, when doing cubic root of negative numbers you always get complex numbers in python.
>>> -1636.281**(1/3)
-11.783816270504108
>>> (-1636.281)**(1/3)
(5.891908135252055+10.205084243784958j)
If you want real numbers you can add code like -
def cube(x):
if x >= 0:
return x**(1/3)
elif x < 0:
return -(abs(x)**(1/3))
Cube root of negative numbers in a numpy array returns nan
In Python, (-1000)**(1/3.)
returns a complex number,
>>> (-1000)**(1/3.)
(5+8.660254037844384j)
This happens because the way computer store numbers, 1/3 = 0.33333...
is an irrational number which at some point gets approximated and therefore there is a loss in precision
>>> a = np.arange(10)**3
>>> a[:6:2] = -1000
>>> a
array([-1000, 1, -1000, 27, -1000, 125, 216, 343, 512,
729], dtype=int32)
>>> for i in a:
print((i)**(1/3.))
nan
1.0
nan
3.0
nan
4.999999999999999
5.999999999999999
6.999999999999999
7.999999999999999
8.999999999999998
Here the values in the ndarray a
are of numpy.int32
type.
The code (i)**(1/3.)
returns a result of type numpy.float64
since the second argument is a floating point.
>>> [type((i)**(1/3.)) for i in a]
[<class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>, <class 'numpy.float64'>]
(-1000)**(1/3.)
is a complex number and cannot be stored as as numpy.float64
therefore nan
To avoid the nan
you can change the dtype
of the ndarray
to numpy.complex
and do the calculations
>>> b = a.astype(np.complex)
>>> b
array([-1000.+0.j, 1.+0.j, -1000.+0.j, 27.+0.j, -1000.+0.j,
125.+0.j, 216.+0.j, 343.+0.j, 512.+0.j, 729.+0.j])
>>> for i in b:
print((i)**(1/3.))
(4.999999999999999+8.660254037844384j)
(1+0j)
(4.999999999999999+8.660254037844384j)
(3+0j)
(4.999999999999999+8.660254037844384j)
(4.999999999999999+0j)
(5.999999999999999+0j)
(6.999999999999999+0j)
(7.999999999999999+0j)
(8.999999999999998+0j)
You can take the absolute values of these numbers using abs()
>>> for i in b:
print(round(abs((i)**(1/3.))))
10.0
1.0
10.0
3.0
10.0
5.0
6.0
7.0
8.0
9.0
Cube root of a negative number
The Java documentation for Math.pow
states:
If the first argument is finite and less than zero [...] [and] if the second argument is finite and not an integer, then the result is NaN.
You could use Math.cbrt
to get the cube root:
double result = Math.cbrt(-8.0);
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.
Calculating the cubic root for negative number
The easiest way would be to write your own function that does something like this:
private static double CubeRoot(double x) {
if (x < 0)
return -Math.Pow(-x, 1d / 3d);
else
return Math.Pow(x, 1d / 3d);
}
Calculating cubic root for negative number
You can use this snippet to calculate it. It also works for other powers, e.g. 1/4
, 1/5
, etc.
function nthroot(x, n) {
try {
var negate = n % 2 == 1 && x < 0;
if(negate)
x = -x;
var possible = Math.pow(x, 1 / n);
n = Math.pow(possible, n);
if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
return negate ? -possible : possible;
} catch(e){}
}
nthroot(-8, 3);
Source: http://gotochriswest.com/blog/2011/05/06/cube-root-an-beyond/
A faster approach for just calculating the cubic root:
Math.cbrt = function(x) {
var sign = x === 0 ? 0 : x > 0 ? 1 : -1;
return sign * Math.pow(Math.abs(x), 1 / 3);
}
Math.cbrt(-8);
Update
To find an integer based cubic root, you can use the following function, inspired by this answer:
// positive-only cubic root approximation
function cbrt(n)
{
var a = n; // note: this is a non optimized assumption
while (a * a * a > n) {
a = Math.floor((2 * a + (n / (a * a))) / 3);
}
return a;
}
It starts with an assumption that converges to the closest integer a
for which a^3 <= n
. This function can be adjusted in the same way to support a negative base.
How to take the cube root of a negative number in VBA for Excel?
Try using the POWER()
function:
POWER(-2, 1/3)
Related Topics
Increase Space Between Bars in Ggplot
Change the Number of Breaks Using Facet_Grid in Ggplot2
Represent Numeric Value with Typical Dollar Amount Format
How to Have Na's Displayed First Using Arrange()
Handle Continuous Missing Values in Time-Series Data
Unknown Timezone Name in R Strptime/As.Posixct
Ggplot2: Fix Colors to Factor Levels
Dplyr::Do() Requires Named Function
Got Message Unable to Load Shared Object Stats.So When R Starts
R Optimization with Equality and Inequality Constraints
Passing Along Ellipsis Arguments to Two Different Functions
Show Content for Menuitem When Menusubitems Exist in Shiny Dashboard
Subset Data.Table by Logical Column
How to Find Difference Between Values in Two Rows in an R Dataframe Using Dplyr