Calculating (rational) roots of negative numbers in python

It is not possible to calculate the cubic root of a negative number in python using regular functions from scipy and sympy. Here is a quick and dirty solution for the problem using scipy. An analog can be written using sympy.

import scipy as sc

def rationalPower(x,r=1/3.0):

    y = sc.absolute(x)**r

    z = sc.int8(x<0)

    return (1-z)*y – z*y

Examples:

>> rationalPower (-8)

-2.o

Advertisements