Python 中的 random.getstate() 函数用于检索捕获随机数生成器当前内部状态的对象。此对象稍后可以传递给 setstate() 方法,以将生成器恢复到此状态。此函数是 random 模块的一部分,该模块提供各种函数来生成随机数和序列。
此函数的主要目的是捕获生成器在特定时刻的状态,然后恢复此状态以有效地再现相同的随机值。
这个函数不能直接访问,所以我们需要导入 random 模块,然后我们需要使用 random 静态对象调用这个函数。
语法
以下是 Python random.getstate() 函数的语法 -
random.getstate()
参数
此函数不接受任何参数。
返回值
random.getstate() 函数返回一个包含生成器当前内部状态的对象。
例让我们看一个如何使用 random.getstate() 函数捕获和恢复随机数生成器状态的示例。
import random
# Initialize the random number generator
random.seed(42)
# Generate a sample of 10 numbers from a range of 20
print(random.sample(range(30), k=10))
# Capture the current state
state = random.getstate()
# Generate a sample of 20 numbers from a range of 20
print(random.sample(range(20), k=20))
# Restore the state
random.setstate(state)
# Generate another sample of 10 numbers from the same range
print(random.sample(range(20), k=10))
当我们运行上述程序时,它会产生以下结果——
[20, 3, 0, 23, 8, 7, 24, 4, 28, 17]
[2, 18, 13, 1, 0, 16, 3, 17, 8, 9, 15, 11, 12, 5, 6, 4, 7, 10, 14, 19]
[2, 18, 13, 1, 0, 16, 3, 17, 8, 9]
[2, 18, 13, 1, 0, 16, 3, 17, 8, 9, 15, 11, 12, 5, 6, 4, 7, 10, 14, 19]
[2, 18, 13, 1, 0, 16, 3, 17, 8, 9]
例
在此示例中,我们将演示如何使用 random.getstate() 函数捕获随机数生成器的状态,然后恢复它以生成相同的随机数序列。
import random
# Initialize the random number generator and get state
random.seed(0)
initial_state = random.getstate()
# Generate and print random number
print(random.random())
print(random.random())
# Setting the seed back to 0 resets the RNG back to the original state
random.seed(0)
new_state = random.getstate()
assert new_state == initial_state
# Since the state of the generator is the same as before, it will produce the same sequence
print(random.random())
# We could also achieve the same outcome by resetting the state explicitly
random.setstate(initial_state)
print(random.random())
上述代码的输出如下 -
0.8444218515250481
0.7579544029403025
0.8444218515250481
0.8444218515250481
0.7579544029403025
0.8444218515250481
0.8444218515250481
例
这是另一个示例,它比较了使用 random.seed()、random.getstate() 和 random.setstate() 函数生成随机数所花费的时间。
import random
import timeit
# Measure the time taken to generate random numbers using seed()
t1 = timeit.timeit(stmt="""random.seed(42)
random.randint(1, 10)""", number=10000, setup="import random")
# Measure the time taken to generate random numbers using getstate() and setstate()
t2 = timeit.timeit(stmt="""random.randint(1, 10)
random.setstate(state)""", number=10000, setup="""import random
state = random.getstate()""")
print("Time taken using seed():", t1)
print("Time taken using getstate() and setstate():", t2)
以下是上述代码的输出 -
Time taken using seed(): 0.11702990002231672
Time taken using getstate() and setstate(): 0.06300339999143034
Time taken using getstate() and setstate(): 0.06300339999143034