Using NumPy randint with Step
In NumPy, the randint function does not directly support a step parameter like arange. However, you can simulate this behaviour by generating a random integer and scaling it using the step value.
Concept Overview
- randint generates random integers within a range.
- It does not support step size directly.
- You can divide the range by the step and multiply the result back.
Interactive Demo
Try changing the values below to simulate how NumPy logic works.
Start: Stop: Step:Result
Click Generate
Basic NumPy Example
Step 1 — Import NumPy
import numpy as np
Step 2 — Define Start, Stop and Step
start = 0
stop = 20
step = 5
Step 3 — Generate Random Number
random_number = np.random.randint(start // step, stop // step) * step
print(random_number)
Python Console Example
>>> import numpy as np >>> start = 0 >>> stop = 20 >>> step = 5 >>> np.random.randint(start // step, stop // step) * step 10Possible outputs:
- 0
- 5
- 10
- 15
Full Example
Generate Multiple Random Numbers
import numpy as np
start = 10
stop = 100
step = 10
random_numbers = [
np.random.randint(start // step, stop // step) * step
for _ in range(5)
]
print(random_numbers)
Example Output
[70, 90, 10, 60, 40]
Explanation
Why divide by step?
Dividing by step shrinks the range so that randint generates an index instead of the actual stepped number.
Why multiply by step?
Multiplying restores the stepped values.
๐ก Key Takeaways
- np.random.randint() does not support step values.
- You can simulate steps by scaling numbers.
- Divide the range using integer division.
- Multiply the result by the step value.
- This method works for any numeric interval.
No comments:
Post a Comment