I'm looking for a function like range except that the step is a fraction of the previous number generated. So if the fraction was 99/100 the set of numbers might be something like this: 100, 99, 98.01... 0.001
Would this be more efficiently done with a for-loop and range-like function or with just a while-loop?
The code I have so far:
stop = .001
current = 100
while current > stop:
#code
current *= 0.99
You can use np.geomspace
:
np.geomspace(100, 12.5, 4)
You can use np.arange
with direct exponentiation:
12.5 * 2**np.arange(3, -1, -1)
np.logspace
is also an option:
100 * np.logspace(0, -3, 4, base=2)
Here is a function that does that:
def fract(current, stop, fraction):
l=[current]
while l[-1]>stop:
l.append(l[-1]*fraction)
return l
>>> fract(100, 0.001, 0.5)
[100, 50.0, 25.0, 12.5, 6.25, 3.125, 1.5625, 0.78125, 0.390625, 0.1953125, 0.09765625, 0.048828125, 0.0244140625, 0.01220703125, 0.006103515625, 0.0030517578125, 0.00152587890625, 0.000762939453125]
If you don't want the last item (it's smaller than stop) just add l.pop()
before the return
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.