首页 > 解决方案 > python numpy exponentially spaced samples between a start and end value

问题描述

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.

标签: pythonnumpy

解决方案


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.]

推荐阅读