Sunday, October 27, 2019

Generating log ranges in Python

Originally Posted on  by hsauro

This is a very short blog on how to generate logarithmic ranges in python:

import numpy as np

# Brute force
x = [0.1, 1, 10, 100, 1000]

# Classic explicit loop
x = 0.1
for i in range (5):
    print (x)
    x = x*10
    
# List comprehension, more efficient
x = [10**i for i in range(-1,3)]
print (x)

# Lazy-evaluation (saves memory for very large lists)
for x in (10**i for i in range(-1,3)):
    print (x)
    
# Using the built-in function in numpy
x = np.logspace (-2,2,num=5)
print (x)