Cubic root of the negative number on python

Viewed 17530

Can someone help me to find a solution on how to calculate a cubic root of the negative number using python?

>>> math.pow(-3, float(1)/3)
nan

it does not work. Cubic root of the negative number is negative number. Any solutions?

14 Answers

numpy has an inbuilt cube root function cbrt that handles negative numbers fine:

>>> import numpy as np
>>> np.cbrt(-8)
-2.0

This was added in version 1.10.0 (released 2015-10-06).

Also works for numpy array / list inputs:

>>> np.cbrt([-8, 27])
array([-2.,  3.])

New in Python 3.11

There is now math.cbrt which handles negative roots seamlessly:

>>> import math
>>> math.cbrt(-3)
-1.4422495703074083
Related