numpy range created using percentage increment

Viewed 602

I would like to create a numpy range from start to stop using a (fixed) percentage increment based on the previous number eg start=100 increment=2% to get 100, 102, 104.04, 106.12 etc

Obviously this can be done by iterating over a list or, more elegantly, using a generator:

def pct_incrementer(start, stop, step_pct):
    val = start
    yield val
    while True:
        val += val * step_pct
        if val >= stop:
            break
        yield val

 np.array(list(pct_incrementer(100, 200, 0.02)))
 # or (as I've just learned!)
 np.fromiter(pct_incrementer(100, 200, 0.02), float)  

Does numpy (or pandas) have a function to do this natively?? (cos I can't find one!). Is there, perhaps a way of manipulating np.array([100] * 10) to do the same thing?

Thanks!

3 Answers
xs = 100 * np.full(np.log(2.0)/np.log(1.02),1.02).cumprod()

appears to now be throwing an error:

TypeError 'numpy.float64' object cannot be interpreted as an integer

Updated to:

xs = 100 * np.full(int(np.log(2.0)/np.log(1.02)),1.02).cumprod()

or more succinctly:

xs1 = 100 * np.full(5,1.02).cumprod()

resulting

array([102. , 104.04  , 106.1208  , 108.243216  , 110.40808032])
import numpy as np
start = 120
end = 255
display=[start]
 while True:
    xs1 = start * np.full(1,1.02).cumprod()
    if xs1.item(0)>=end:
        break
    else:
        display.append(xs1.item(0))
        start=xs1.item(0)
display = [ round(elem, 2) for elem in display ]
print(display)

#Result: [120, 122.4, 124.85, 127.34, 129.89, ... 254.68]

this method is 20-40 times faster. Hope this helps :)

Related