随机种子的作用域

当随机种子设置之后,会作用于从设置该随机种子开始,一直到程序结束,或者是再次设置随机种子的时候。

import numpy as np



def seed_a():
    np.random.seed(0)
    a = np.random.rand((1))
    print('a: ', a)
    return a

def function_b():
    b_before = np.random.rand((1))
    print('b_before:', b_before)
    seed_a()
    b_after = np.random.rand((1))
    print('b_after: ', b_after)
    seed_a()

function_b()

输出:
b_before: [0.40310648]
a: [0.5488135]
b_after: [0.71518937]
a: [0.5488135]

其中b_before每次的值是随机的,第一个a与第二个a的值保持相同,b_after的值会在每次重新运行的时候保持相同。

这说明在seed_a设置随机种子之后,会影响到调用seed_a函数的function_b函数

猜你喜欢

转载自blog.csdn.net/weixin_42173136/article/details/131558549
今日推荐