python numpy exponentially spaced samples between a start and end value

Viewed 6783

numpy.linspace generates evenly spaced float samples between a start and end value.

print (numpy.linspace(0.0, 1.0, num=9))

# [0 0.125 0.25 0.375 0.5  0.625 0.75  0.875 1]

print (numpy.linspace(9000.0, 1000.0, num=9))

# [9000. 8000. 7000. 6000. 5000. 4000. 3000. 2000. 1000.]

How can I generate exponentially spaced samples between a start and end value ?


For example, to the power of 2:

[0. 0.016 0.0625 0.141 0.25 0.391 0.562 0.766 1.]

Thanks for any suggestions.

3 Answers

For the case of going between 0 and 1, you can just take the square of the array:

print (numpy.linspace(0.0, 1.0, num=9)**2 )
# [0. 0.016 0.0625 0.141 0.25 0.391 0.562 0.766 1.]

or

print (numpy.power(numpy.linspace(0.0, 1.0, num=9), 2) )
# [0. 0.016 0.0625 0.141 0.25 0.391 0.562 0.766 1.]

Edit:

A more generalized approach could be to 1) take the inverse power of the start and stop numbers, 2) get the linear spacing between those values, 3) return the array raised to the power.

import numpy as np

def powspace(start, stop, power, num):
    start = np.power(start, 1/float(power))
    stop = np.power(stop, 1/float(power))
    return np.power( np.linspace(start, stop, num=num), power) 

print( powspace(0, 1, 2, 9) )
# [0. 0.016 0.0625 0.141 0.25 0.391 0.562 0.766 1.]

Then you can go between any positive values. For example, going from 9000 to 1000 with values spaced to the power of 3:

print( powspace(9000, 1000, 3, 9) )
# [9000. 7358.8 5930.4 4699.9 3652.6 2773.7 2048.5 1462.2 1000.]

You can use np.logspace such that:

np.logspace(-9, 0, base=2, num=10)

which is equivalent to power(base, y)

EDIT

The answer mentions exponential spaced, then the squares of values.

This answer is actually exponential spaced, i.e. 2^x. The values x^2 is not exponential space, but polynomial.

If you're ok with powers of 10, why not just:

import numpy as np

def powspace(start: float, stop: float, num: int):
  log_start, log_stop = np.log(start), np.log(stop)
  return np.exp(np.linspace(log_start, log_stop, num))

>>> powspace(9000, 1000, 9)
>>> array([9000.        , 6838.52117086, 5196.15242271, 3948.22203886,
       3000.        , 2279.50705695, 1732.05080757, 1316.07401295,
       1000.        ])


Related