I'm using x = numpy.random.rand(1) to generate a random number between 0 and 1. How do I make it so that x > .5 is 2 times more probable than x < .5?
That's a fitting name!
Just do a little manipulation of the inputs. First set x to be in the range from 0 to 1.5.
x = numpy.random.uniform(1.5) x has a 2/3 chance of being greater than 0.5 and 1/3 chance being smaller. Then if x is greater than 1.0, subtract .5 from it
if x >= 1.0: x = x - 0.5
This is overkill for you, but it's good to know an actual method for generating a random number with any probability density function (pdf).
You can do that by subclassing scipy.stat.rv_continuous, provided you do it correctly. You will have to have a normalized pdf (so that its integral is 1). If you don't, numpy will automatically adjust the range for you. In this case, your pdf has a value of 2/3 for x<0.5, and 4/3 for x>0.5, with a support of [0, 1) (support is the interval over which it's nonzero):
import scipy.stats as spst import numpy as np import matplotlib.pyplot as plt import ipdb def pdf_shape(x, k): if x < 0.5: return 2/3. elif 0.5 <= x and x < 1: return 4/3. else: return 0. class custom_pdf(spst.rv_continuous): def _pdf(self, x, k): return pdf_shape(x, k) instance = custom_pdf(a=0, b=1) samps = instance.rvs(k=1, size=10000) plt.hist(samps, bins=20) plt.show() 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With