python中seed 5,Python中的Seed()和随机数

Today, I was just told about the seed() function from a programmer much more experienced than me. I normally just call choice() with a list as an argument, as I don't need anymore random number functionality than that.

My programmer friend told me that calling seed is necessary because otherwise Python always begins random number operations with zero as the default seed. This means that although the numbers appear random, we are really getting the same sequence every time.

This strikes me as rather odd. Does the choice() function, for example, really not call seed before it does its thing? Or is the reason it can't programmatically change its seed because that in of itself would involve picking a random number, and obviously that it is a bit of a problem if our end goal is also to pick a random number!

I'm ranting a bit here, but I'm wondering if anyone has a clear idea of how all this was implemented.

解决方案

Your friend is dead wrong, and would know so if he read the documentation for the seed() function:

Initialize the basic random number generator. Optional argument x can be any hashable object. If x is omitted or None, current system time is used; current system time is also used to initialize the generator when the module is first imported. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

(Emphasis mine.)

He's guessing based on his knowledge of how it works in other languages. The seed() function is mainly provided so that you can get a reproducible stream of pseudorandom numbers (which is necessary for some specific applications).

The functions you call directly from the random module are actually aliases to methods of a hidden instance of the random.Random class. Each instance, at least in effect, calls seed() within its __init__().

The choice() function obviously does not call seed() before operation, because that would mean re-seeding before every choice, which defeats the purpose of seeding.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值