Python random.getrandbits()
random模块用于在Python中生成随机数。实际上不是随机的,而是用于生成伪随机数。这意味着这些随机生成的数字可以被确定。
random.getrandbits()
随机模块的getrandbits()方法用于返回一个具有指定比特数的整数。结果中所需要的位数作为参数在该方法中传递。例子:
Input : getrandbits(4)
Output : 14
(the binary equivalent of 14 is 1110 which has 4 bits)
Input : getrandbits(16)
Output : 60431
(the binary equivalent of 60431 is 1110110000001111
which has 16 bits)
例1:
# import the random module
import random
# a random number with 4 bits
print(random.getrandbits(4))
# a random number with 16 bits
print(random.getrandbits(16))
输出:
10
49195
例2:
# import the random module
import random
# 5 random number with 4 bits
for i in range(4):
print(random.getrandbits(4))
输出:
10
0
1
14