user1551817
user1551817

Reputation: 7461

Produce an object similar to scipy.stats.uniform() that will allow the exclusion of a specified range

I'm trying to modify some existing python code.

The line in the code that I want to change is:

scipy.stats.uniform(0.0, 100.0)

So this gives me a uniform continuous random variable between 0 and 100.

I want to achieve almost the same output, but I want to have certain ranges that are not included. For example, I might want the variable to be uniform between 0 and 70, and between 80 and 100. In other words, I just want to cut 70 to 80 out of the range.

Obviously I know how to just produce a range with numbers missing, but I'm confused by the fact that is a specific type of object. I need my output to be the same type of scipy.stats._continuous_distns.uniform_gen object to work with the rest of the code.

Is there anything existing that would allow me to do that?

Thanks!

Upvotes: 0

Views: 162

Answers (1)

ev-br
ev-br

Reputation: 26060

Use rv_histogram for piecewise constant PDFs. The PDF can be zero in a range of values, too:

In [1]: import numpy as np

In [2]: bins = np.array([0, 70, 80, 100])

In [3]: vals = np.array([1.0, 0.0, 1.0])

In [4]: vals = vals * (bins[1:] - bins[:-1])   # normalize the PDF

In [5]: vals /= vals.sum()

In [6]: import scipy.stats as stats

In [7]: rv = stats.rv_histogram((vals, bins))

In [8]: sample = rv.rvs(size=10000)

In [9]: ((70 < sample) & (sample < 80)).any()

Out[9]: False

(Note that you need to normalize the PDF manually). If you want non-constant PDFs, then you'll need to subclass scipy.stats.rv_continuous and provide implementations of _pdf etc.

Upvotes: 1

Related Questions