numpy/rng-in-loop
| Pack | Severity | Fix | Versions |
|---|---|---|---|
| NumPy | warning | none, edit by hand | All versions |
np.random.default_rng() inside a loop builds a new Generator on every pass. Create it once before the loop and draw from it.
noise = [np.random.default_rng().normal() for _ in range(n)]rng = np.random.default_rng()noise = rng.normal(size=n)What the rule reports
Section titled “What the rule reports”The rule reports np.random.default_rng() without a seed inside a for or while body or a comprehension. Each call gathers entropy, the random bits for a seed, from the operating system, which takes about 5 microseconds. The rule leaves a loop alone that seeds each pass from its loop variable.
A constant seed is also left alone. It repeats the same stream on each pass.
How to fix it
Section titled “How to fix it”xpd has no automatic fix, so make the change by hand.
Diagnostic message
Section titled “Diagnostic message”$NP.random.default_rng() builds a new Generator on every pass, which costs about 5 microseconds each time. Create rng = $NP.random.default_rng() once before the loop and draw from it.See all rules in the NumPy pack.