python - 如何在 Python 中生成指数增长的范围

标签 python

我想使用指数增长的值来测试一些代码的性能。因此,当一个额外的数字被添加到 numbers_size 时,增量会乘以 10。到目前为止,我就是这样做的,但它看起来有点老套。在不引入非标准库的情况下提出改进建议?

numbers_size = 100
increment = 100
numbers_range = 1000000000
while numbers_size < numbers_range:
    t = time.time()
    test( numbers_size )
    taken_t = time.time() - t
    print numbers_size, test, taken_t

    increment = 10 ** (len(str(numbers_size))-1)
    numbers_size += increment

最佳答案

如果您将 numpy 视为标准之一 ;),您可以使用 numpy.logspace因为这是它应该做的....(注意:100=10^2,1000000000=10^9)

for n in numpy.logspace(2,9,num=9-2, endpoint=False):
    test(n)

例子2(注意:100=10^2, 1000000000=10^9, 想一步10x,就是9-2+1点...):

In[14]: np.logspace(2,9,num=9-2+1,base=10,dtype='int')
Out[14]: 
array([       100,       1000,      10000,     100000,    1000000,
         10000000,  100000000, 1000000000])

示例 3:

In[10]: np.logspace(2,9,dtype='int')
Out[10]: 
array([       100,        138,        193,        268,        372,
              517,        719,       1000,       1389,       1930,
             2682,       3727,       5179,       7196,      10000,
            13894,      19306,      26826,      37275,      51794,
            71968,     100000,     138949,     193069,     268269,
           372759,     517947,     719685,    1000000,    1389495,
          1930697,    2682695,    3727593,    5179474,    7196856,
         10000000,   13894954,   19306977,   26826957,   37275937,
         51794746,   71968567,  100000000,  138949549,  193069772,
        268269579,  372759372,  517947467,  719685673, 1000000000])

在您的情况下,我们使用 endpoint=False 因为您不想包含端点...(例如 np.logspace(2,9,num=9-2, endpoint =假))

关于python - 如何在 Python 中生成指数增长的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443737/

相关文章:

python - 安装脚本已退出,出现错误 : command 'x86_64-linux-gnu-gcc' failed with exit status 1 while Installing PyNaCl

Python-在字符串中插入一个字符

python - Cython纯python模式

python - Scrapy提取错误的IMG SRC

python - "' 模块 ' object has no attribute ..."多处理错误

python - 迭代 pandas Series 仅执行一次

Python:如何使用 lxml 解析带句点的 xml 标签?

python - 检查时间戳是否在两列之间

python - 在 Pandas 中计算 YTD 总数

python - 正则表达式消除 bibtex 文件中的字段