Exponential powers with range

Viewed 2146

I'm having a problem with my code

def bconver(n,b):
    for i in range(n):
        x = b ** i

I am trying to have b to the power of all the i values from the range of n. I need to be able to take those values and divide them by n allowing me to change it to any base.

I have tried this code but it doesn't work since I can't divide those values after. Also, I need the answers not in a list

x = [b ** i for i in range(n)]  
2 Answers

You can divide each value in your list comprehension by n:

x = [b ** i for i in range(n)]  
x_over_n = [a/n for a in x]

edit:

def x_to_the_i_over_n(x, i, n):
    return x**i / n

n = 4
x = 123
results = []
for i in range(n):
    results.append(x_to_the_i_over_n(x, i, n))

edit 2:

import numpy

b = numpy.array(range(10))
b**2
#--> array([ 0,  1,  4,  9, 16, 25, 36, 49, 64, 81])

b**2 / 4
#--> array([  0.  ,   0.25,   1.  ,   2.25,   4.  ,   6.25,   9.  ,  12.25, 16.  ,  20.25])

You can perform any operations you want inside that list comprehension. For example,

x = [(b ** i) / n for i in range(n)]

sounds like the final result you're looking for. If you want the intermediate result, just use another list comprehension:

x = [b ** i for i in range(n)]
x_divided_by_n = [element / n for element in x]

If you want more compact ways to express these kinds of operations, look into using numpy.

Related