Ghilas BELHADJ - 1 year ago 242

Python Question

How to generate a random integer as with

`np.random.randint()`

`np.random.randint(-10, 10)`

`np.random.normal(0, 0.1, 1)`

What I want is a kind of combination between the two functions.

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

Answer Source

One other possible way to get a discrete distribution that *looks like* the normal distribution is to draw from a multinomial distribution where the probabilities are calculated from a normal distribution.

```
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(-10, 11)
xU, xL = x + 0.5, x - 0.5
prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3)
prob = prob / prob.sum() #normalize the probabilities so their sum is 1
nums = np.random.choice(x, size = 10000, p = prob)
plt.hist(nums, bins = len(x))
```

Here, `np.random.choice`

picks an integer from [-10, 10]. The probability for selecting an element, say 0, is calculated by p(-0.5 < x < 0.5) where x is a normal random variable with mean zero and standard deviation 3. I chooce std. dev. as 3 because this way p(-10 < x < 10) is almost 1.

The result looks like this:

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