Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

logarithmically spaced range centered around a value in python?

Tags:

python

I need to create an array of values within two bounds (e.g. 1 and 100) where the values are logarithmically spaced with respect to some center (e.g. 50). That is: most values should be close to 50 but move away toward 1 or 100 in exponential steps.

I have tried the np.geomspace() function

def sample_exponentially(center,N,lower_bound, upper_bound):
    lower_bound_to_center=np.geomspace(center,lower_bound,num=N/2)
    upper_bound_to_center=np.geomspace(center,upper_bound, num=N/2)
    lower_bound_to_center = center - lower_bound_to_center
    return lower_bound_to_center.tolist() + upper_bound_to_center.tolist()

But the result is the following:

results plot image

The two halves of the distribution are on different scales. I guess it's because np.geomspace() works with the transformation of the actual input values. Does anyone know of a function that would give me a symmetrical distribution for a case like my example where the space between the center and each bound is equal?

like image 390
Mark Hastings Avatar asked Jan 24 '26 22:01

Mark Hastings


1 Answers

In order to get a tight distribution around your center point, you should generate the progression from 1 and add center afterward (or subtract from it):

import numpy as np
center      = 50
lower_bound = 1
upper_bound = 100
N           = 12
upper_bound_to_center = center + np.geomspace(1,upper_bound-center, num=N/2)
lower_bound_to_center = center - np.geomspace(1,center-lower_bound, num=N/2)
result = list(lower_bound_to_center) + list(upper_bound_to_center)

from matplotlib import pyplot
pyplot.plot(result, [1]*len(result), 'ro')
pyplot.show()

enter image description here

like image 170
Alain T. Avatar answered Jan 27 '26 11:01

Alain T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!