播种和重复使用Python随机种子 [英] Seeding and reusing Python random seeds

查看:216
本文介绍了播种和重复使用Python随机种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python和Flask来显示一个随机游戏板,并试图通过使用种子来让人们返回到同一个游戏。不过,无论我使用随机种子还是指定种子,我似乎都得到了相同的伪随机序列。

我把大部分代码都剪掉了(我做了很多分裂并加入numpy),但是即使是下面的简单代码也显示了这个bug:不管什么值种子我给表格,提交时显示的数字是一样的。在不指定种子的情况下提交表单会显示一个不同的数字,但是尽管在重新加载时显示不同的种子值,那么其他数字也总是相同。



错误的种子?

  from flask import Flask,request,render_template 
import numpy as np
import random
$ b app = Flask(__ name__)

@ app.route('/')
def single_page():
return render_template('page。 html',title ='empty form')

@ app.route('/ number',methods = ['POST','GET'])
def render_page(title =生成的随机数',错误= []):
error = []
如果request.method =='POST':$ b $如果request.form ['seed']。isdigit() :
seed = int(request.form ['seed'])
error.append(seed set:+ str(seed)+。)
np.random.seed (种子/ 100000)
else:
seed = int(100000 * random (seed)/)
np.random.seed(seed / 100000)

n = np.random.random()* 100;

return render_template('page.html',title = title,error = error,n = n,seed = seed)

else:
return render_template 'page.html',title ='empty form')

if __name__ =='__main__':
app.debug = True
app.run()

以下是烧瓶HTML模板

 <!doctype html> 
< html>
< head>< title> {{title}}< / title>
< / head>
< body>
{%if if error!=''%}
{%for message in error%}
< h2> {{message}}< / h2>
{%endfor%}
{%endif%}

{%if n%}
< h2>随机数是{{n} / H2>

< h6> seed = {{seed}}< / h6>
{%else%}
< div id =form>
< form id =the_formmethod =POSTaction =number>
种子:< input type =numbermin =1max =99999id =seedname =seed>< br>
< button id =submittype =submit>提交< / button>
< / form>
{%endif%}
< / div>
< / body>
< / html>

我们将种子乘以100,000以便给出一个更难忘的值(比如说4231 4.231479094 ...)。是否有更好的方法来使用可用的整数种子值?



更新:
是的,还有更好的方法整数种子值 - 不要混乱分割。暂时这就是我所做的:

pre $ $ $ $ $ $进口numpy as np
进口随机



if request.form ['seed']。isdigit():
seed = int(request.form ['seed'])
error.append(seed set:+ str (seed)+。)
random.seed(seed)
else:
seed = int(100000 * np.random.random())
error.append( 种子没有设置,+ str(种子)+而不是。)
random.seed(种子)

n = random.random()* 100;

return render_template('page.html',title = title,error = error,n = n,seed = seed)

这工作正常。 np.random.seed()似乎总是得到相同的序列,但random.seed()不介意整数,所以我使用后者。



  7078/100000 = 0 

如果种子是<>,则总是给出零的种子。 100000.有了这个:

  np.random.seed(seed)
pre>

种子应该改变。没有参数 np.random.seed 应该尝试取(依赖于系统的)种子。



如果你想要阅读PIP上的修复这个部门:请参阅 PEP 238 。在Python 3中,Python 2.X 2/5 = 0 中的 2/5 = 0.4 。您可以通过包含以下行来强制在代码的顶部添加浮点: $ _
$ b

  from __future__ import division 

为什么使用 np.random 而不是Python的 random



文档


Python stdlib模块随机还包含一个Mersenne Twister伪随机数生成器,其中有许多方法类似于RandomState中可用的方法。 RandomState除了具有NumPy意识之外,还具有提供更多选择概率分布的优点。


I'm using Python and Flask to display a randomized game board, and trying to allow people to return to the same game by using a seed.

However, whether I use a random seed, or specify a seed, I seem to get the same pseudorandom sequences.

I cut out the majority of my code (I do a lot of splitting and joining with numpy) but even the simple code below shows the bug: no matter what value of seed I give the form, the number displayed on submit is the same. Submitting the form without specifying the seed shows a different number, but despite showing different seed values on reloading, that other number is always the same as well.

Am I doing something wrong with seeding?

from flask import Flask, request, render_template
import numpy as np
import random

app = Flask(__name__)

@app.route( '/' )
def single_page():
   return render_template( 'page.html', title = 'empty form' )

@app.route( '/number', methods = [ 'POST', 'GET' ] )
def render_page( title = 'generated random number', error = [] ):
   error = []
   if request.method == 'POST':
      if request.form['seed'].isdigit():
         seed = int( request.form['seed'] )
         error.append( "seed set: " + str( seed ) + "." )
         np.random.seed( seed/100000 )
      else:
         seed = int( 100000 * random.random() )
         error.append( "seed not set, " + str( seed ) + " instead." )
         np.random.seed( seed/100000 )

      n = np.random.random() * 100;

      return render_template('page.html', title=title, error=error, n=n, seed=seed )

   else:
      return render_template( 'page.html', title = 'empty form' )

if __name__ == '__main__':
   app.debug = True
   app.run()

Here is the flask HTML template

<!doctype html>
<html>
<head><title>{{title}}</title>
</head>
<body>
{% if error != '' %}
{% for message in error %}
    <h2>{{message}}</h2>
{% endfor %}
{% endif %}

{% if n %}
    <h2>Random number is {{n}}</h2>

    <h6>seed = {{ seed }}</h6>
{% else %}
    <div id="form">
    <form id="the_form" method="POST" action="number">
    Seed: <input type="number" min="1" max="99999" id="seed" name="seed"><br>
    <button id="submit" type="submit">Submit</button>
    </form>
{% endif %}
</div>
</body>
</html>

I multiply and divide the seeds by 100,000 so as to give a more memorable value (say, 4231 instead of 4.231479094...). Is there is a better way to have usable integer seed values?

UPDATED: Yes, there is a better way to do integer seed values - not mess with dividing at all. For the time being this is what I'm doing:

import numpy as np
import random
.
.
.
      if request.form['seed'].isdigit():
         seed = int( request.form['seed'] )
         error.append( "seed set: " + str( seed ) + "." )
         random.seed( seed )
      else:
         seed = int( 100000 * np.random.random() )
         error.append( "seed not set, " + str( seed ) + " instead." )
         random.seed( seed )

      n = random.random() * 100;

      return render_template('page.html', title=title, error=error, n=n, seed=seed )

This works fine. np.random.seed() didn't seem to always get the same sequence, but random.seed() doesn't mind an integer, so I'm using the latter.

解决方案

Your seed is probably an integer and integer division in early Python won't give a float. Thus

7078 / 100000 = 0

This always gives a seed of zero if seed is < 100000. With this:

np.random.seed( seed )

The seed should change. Without an argument np.random.seed should try to take a (system-dependent) seed.

If you want to read up on the PIP that "fixes" this the division: see PEP 238. In Python 3 this 2/5=0.4 in Python 2.X 2/5=0. You can force floating point upcasting at the top of your code by including the line:

from __future__ import division

Why use np.random instead of Python's random?

From the documentation:

The Python stdlib module "random" also contains a Mersenne Twister pseudo-random number generator with a number of methods that are similar to the ones available in RandomState. RandomState, besides being NumPy-aware, has the advantage that it provides a much larger number of probability distributions to choose from.

这篇关于播种和重复使用Python随机种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆