Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cubic root of the negative number on python

Tags:

python

math

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?

like image 225
Vladimir Prudnikov Avatar asked Sep 01 '09 10:09

Vladimir Prudnikov


People also ask

How do you find the cube root of a negative number in Python?

To find the cube root of a negative number in Python, first, use the abs() function, and then you can use the simple math equation to calculate the cube root.

Can you cubic root a negative number?

Cube Root: Cube root of a number is the value that, when multiplied by itself three times, yields the number. The cube root of a positive number is always positive, and the cube root of a negative number is always negative.

How do you handle negative numbers in Python?

In Python, positive numbers can be changed to negative numbers with the help of the in-built method provided in the Python library called abs (). When abs () is used, it converts negative numbers to positive. However, when -abs () is used, then a positive number can be changed to a negative number.

Is there root for negative numbers?

Negative numbers don't have real square roots since a square is either positive or 0. The square roots of numbers that are not a perfect square are members of the irrational numbers.


1 Answers

A simple use of De Moivre's formula, is sufficient to show that the cube root of a value, regardless of sign, is a multi-valued function. That means, for any input value, there will be three solutions. Most of the solutions presented to far only return the principle root. A solution that returns all valid roots, and explicitly tests for non-complex special cases, is shown below.

import numpy
import math
def cuberoot( z ):
    z = complex(z)
    x = z.real
    y = z.imag
    mag = abs(z)
    arg = math.atan2(y,x)
    return [ mag**(1./3) * numpy.exp( 1j*(arg+2*n*math.pi)/3 ) for n in range(1,4) ]

Edit: As requested, in cases where it is inappropriate to have dependency on numpy, the following code does the same thing.

def cuberoot( z ):
    z = complex(z) 
    x = z.real
    y = z.imag
    mag = abs(z)
    arg = math.atan2(y,x)
    resMag = mag**(1./3)
    resArg = [ (arg+2*math.pi*n)/3. for n in range(1,4) ]
    return [  resMag*(math.cos(a) + math.sin(a)*1j) for a in resArg ]
like image 192
Andrew Walker Avatar answered Sep 21 '22 05:09

Andrew Walker