python 如何修复 Random 产生的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1805265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fix value produced by Random?
提问by user211037
I got an issue which is, in my code,anyone can help will be great. this is the example code.
我遇到了一个问题,在我的代码中,任何人都可以提供帮助。这是示例代码。
from random import *
from numpy import *
r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)])
def Ft(r):
for i in range(3):
do something here, call r
return something
however I found that in python shell, every time I run function Ft, it gives me different result.....seems like within the function, in each iterate of the for loop,call r once, it gives random numbers once... but not fix the initial random number when I call the function....how can I fix it? how about use b=copy(r) then call b in the Ft function? Thanks
但是我发现在 python shell 中,每次运行函数 Ft 时,它都会给我不同的结果......似乎在函数内部,在 for 循环的每次迭代中,调用 r 一次,它给出一次随机数.. . 但当我调用函数时没有修复初始随机数....我该如何修复它?使用 b=copy(r) 然后在 Ft 函数中调用 b 怎么样?谢谢
回答by Simon Callan
Do you mean that you want the calls to randon.uniform()
to return the same sequence of values each time you run the function?
If so, you need to call random.seed()
to set the start of the sequence to a fixed value. If you don't, the current system time is used to initialise the random number generator, which is intended to cause it to generate a different sequence every time.
您的意思是希望randon.uniform()
每次运行函数时调用都返回相同的值序列吗?
如果是这样,您需要调用random.seed()
将序列的开始设置为固定值。如果不这样做,则当前系统时间用于初始化随机数生成器,目的是使其每次生成不同的序列。
Something like this should work
这样的事情应该工作
random.seed(42) # Set the random number generator to a fixed sequence.
r = array([uniform(-R,R), uniform(-R,R), uniform(-R,R)])
回答by dagoof
I think you mean 'list' instead of 'array', you're trying to use functions when you really don't need to. If I understand you correctly, you want to edit a list of random floats:
我认为您的意思是“列表”而不是“数组”,您是在真正不需要时尝试使用函数。如果我理解正确,您想编辑随机浮点数列表:
import random
r=[random.uniform(-R,R) for x in range(3)]
def ft(r):
for i in range(len(r)):
r[i]=???