Mohammad Amin - 1 year ago 291

Python Question

I need to construct a truncated exponential random variable, bounded between 5 and 7, with a rate parameter equal to 0.76. I am using scipy.stats.truncexpon, with loc=5 and scale=1/0.76. I am not sure how to specify the upper bound though. Any ideas?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

```
import scipy.stats as stats
import matplotlib.pyplot as plt
lower, upper, scale = 5, 7, 1/0.76
X = stats.truncexpon(b=(upper-lower)/scale, loc=lower, scale=scale)
data = X.rvs(10000)
fig, ax = plt.subplots()
ax.hist(data, normed=True)
plt.show()
```

`stats.truncexpon`

is an instance of a subclass of `rv_continuous`

.
The `rv_continuous`

class has `a`

and `b`

parameters which define the lower and upper bound of the support of the distribution. `truncexpon`

has the `a`

parameter fixed at 0:

```
truncexpon = truncexpon_gen(a=0.0, name='truncexpon')
```

Thus by default `truncexpon`

's support goes from `0`

to `b`

.
Per the docs, `truncexpon.pdf(x, b, loc, scale)`

is identically
equivalent to `truncexpon.pdf(y, b) / scale`

with `y = (x - loc) / scale`

.

So as `y`

goes from `0`

to `b`

, `x`

goes from `loc`

to `b*scale + loc`

.
So to make `x`

go from `lower`

to `upper`

, let `loc = lower`

and `b = (upper-lower)/scale`

.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**