In Python, generating random numbers primarily relies on the random module. Here are several commonly used methods:
-
random():
- The
random.random()method returns a random floating-point number between 0 and 1, inclusive of 0 but exclusive of 1. - For example:
python
import random num = random.random() print(num) # outputs something like 0.37444887175646646
- The
-
randint(a, b):
- The
random.randint(a, b)method returns a random integer within the specified range, inclusive of both boundaries a and b. - For example:
python
import random num = random.randint(1, 10) print(num) # outputs an integer between 1 and 10, inclusive of both 1 and 10
- The
-
randrange(start, stop[, step]):
- The
random.randrange(start, stop[, step])method returns a random number within the specified range, allowing specification of a step. - For example:
python
import random num = random.randrange(0, 101, 5) print(num) # outputs a multiple of 5 between 0 and 100
- The
-
uniform(a, b):
- The
random.uniform(a, b)method returns a random floating-point number between a and b, inclusive of a but exclusive of b. - For example:
python
import random num = random.uniform(1.5, 4.5) print(num) # outputs a floating-point number between 1.5 and 4.5
- The
Additionally, to achieve reproducible results, the random.seed() method can be used to set the seed value for the random number generator:
pythonimport random random.seed(10) # sets the seed value print(random.random()) # outputs the same result every time
These are several common methods for generating random numbers in Python.
2024年8月9日 09:57 回复