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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s