Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Can't use fraction exponents

I'm trying to use the pow(x, n) function to take the nth root of x, where n is defined in initialize(context), is named context.n, and is a fraction (typically either 1/2, 1/3, or 1/4). For some reason, it's rounding context.n to the nearest integer, which is 0 in this case, which means my math always evaluates to 1.

Here's a sample for improved readability:

def initialize(context):  
    context.n = 1 / 3

def handle_data(context, data):  
    x = 0.585 / 0.969  
    p = pow(x,context.n) # evaluates to 1  
    logmsg = "\n({num} / {den}) ^ {exp} = {ans}"  
    log.debug(logmsg.format(num=0.585,den=0.969,exp=context.n,ans=p)  

Anybody know what I'm doing wrong?

EDIT: I should point out that I've tried separating context.n into two separate numbers, the numerator and the denominator, and it does the same thing.

2 responses

Simon,
You ran into a really common issue people run into with Python 2.x. When working with integers, the default division type is floor division, you need to use a float in either the numerator or denominator. Change context.n to 1.0 / 3, you should get the answer you are looking for.

David

Brilliant!

Just tried it and it worked

Many thanks,
Simon