How to generate exponentially increasing range in Python

前端 未结 8 1237
醉梦人生
醉梦人生 2020-12-15 23:05

I want to test the performance of some code using an exponentially increasing value. So that as an extra digit is added to the numbers_size the increment is multiplied by 1

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 23:35

    OP wrote "Suggestions for improvements without introducing non-standard libraries?"

    Just for completeness, here's a recipe for generating exponential ranges - each element is a fixed factor bigger than the previous:

    from math import exp
    from math import log
    
    def frange(start, stop, numelements):
        """range function for floats"""
        incr = (stop - start) / numelements
        return (start + x * incr for x in range(numelements))
    
    def exprange(start, stop, numelements):
        """exponential range - each element is a fixed factor bigger than the previous"""
        return (exp(x) for x in frange(log(start), log(stop), numelements))
    

    Test:

    print(", ".join("%.3f" % x for x in exprange(3,81,6)))
    

    Output:

    3.000, 5.196, 9.000, 15.588, 27.000, 46.765
    

提交回复
热议问题