Hamid Shahrokhshahi - 7 months ago 76

Python Question

Guys I am using to generate a random system, and because of it's function, I want to choose the random module in Numpy. but when I wanted to implement it, I realize that Numpy will not really generate a psedu-random number. briefly, the result of following code is 0 every time:

`import numpy as np`

for i in range(10000):

n[i] = np.random.randint(0,1)

as I mentioned, all of the cell's in n have the zero value. even when I add a pause between each iteration i still have the same result.

`import time`

import numpy as np

for i in range(10000):

n[i] = np.random.randint(0,1)

time.sleep(2)

that is not the case when i use the build in random module.

Since this problem could really affect the integrity of my result, I would highly appreciate any command regarding how can I overcome this issue or why is this happening.

PS: that is not the case when i import Numpy in IDLE and simply just print

`np.random.randint(0,1)`

again and again. in this situation the result is look like random.

Answer

The `high`

argument of `numpy.random.randint(low, high)`

is an exclusive range, like `range(low, high)`

. You want `numpy.random.randint(0, 2)`

to have an equal chance of generating a 0 or a 1.

This differs from the standard library's `random.randint()`

, which uses an inclusive range. The inclusive range is broadly considered to be a design mistake. The naming of the two functions is mostly coincidental; `numpy.random.randint()`

descends from `Numeric`

's `RandomArray`

module that predates the standard `random`

module, and was designed for backwards compatibility with `RandomArray`

to ease the transition from `Numeric`

to `numpy`

.

Source (Stackoverflow)