使用 for 循环和范围函数与 while 循环
Using a for-loop and range function vs a while-loop
我正在寻找类似 range 的函数,只是步骤是先前生成的数字的一小部分。因此,如果分数是 99/100,则数字集可能是这样的:100, 99, 98.01... 0.001
使用 for 循环和类似范围的函数还是仅使用 while 循环会更有效?
我目前的代码:
stop = .001
current = 100
while current > stop:
#code
current *= 0.99
您可以使用 np.geomspace
:
np.geomspace(100, 12.5, 4)
您可以使用 np.arange
直接求幂:
12.5 * 2**np.arange(3, -1, -1)
np.logspace
也是一个选项:
100 * np.logspace(0, -3, 4, base=2)
这是一个函数:
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]
如果您不想要最后一项(它小于停止),只需在 return
之前添加 l.pop()
我正在寻找类似 range 的函数,只是步骤是先前生成的数字的一小部分。因此,如果分数是 99/100,则数字集可能是这样的:100, 99, 98.01... 0.001
使用 for 循环和类似范围的函数还是仅使用 while 循环会更有效?
我目前的代码:
stop = .001
current = 100
while current > stop:
#code
current *= 0.99
您可以使用 np.geomspace
:
np.geomspace(100, 12.5, 4)
您可以使用 np.arange
直接求幂:
12.5 * 2**np.arange(3, -1, -1)
np.logspace
也是一个选项:
100 * np.logspace(0, -3, 4, base=2)
这是一个函数:
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]
如果您不想要最后一项(它小于停止),只需在 return
之前添加l.pop()