Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, weighted linspace

Tags:

python

numpy

can anyone show me what the best way is to generate a (numpy) array containig values from 0 to 100, that is weighted by a (for example) normal distribution function with mean 50 and variance 5. So that there are more 50s and less (nearly no) zeros and hundreds. I think the problem should not be too hard to solve, but I'm stucked somehow...

I thought about something with np.linspace but it seems, that there is no weight option.

So just to be clear: I don't wan't a simple normal distribution from 0 to 100, but something like an array from 0 to 100 with higher density of values in the middle.

Thanks

like image 314
wa4557 Avatar asked Oct 24 '25 20:10

wa4557


1 Answers

You can use scipy's stats distributions:

import numpy as np
from scipy import stats

# your distribution:
distribution = stats.norm(loc=50, scale=5)

# percentile point, the range for the inverse cumulative distribution function:
bounds_for_range = distribution.cdf([0, 100])

# Linspace for the inverse cdf:
pp = np.linspace(*bounds_for_range, num=1000)

x = distribution.ppf(pp)

# And just to check that it makes sense you can try:
from matplotlib import pyplot as plt
plt.hist(x)
plt.show()

Of course, I admit the start and end point is not quite exact like this due to numerical inaccuracies when going back and forth.

like image 192
seberg Avatar answered Oct 26 '25 11:10

seberg



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!