Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix value produced by Random?

Tags:

python

random

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

like image 265
user211037 Avatar asked Nov 26 '09 19:11

user211037


2 Answers

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.

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)])
like image 131
Simon Callan Avatar answered Oct 26 '22 22:10

Simon Callan


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]=???
like image 26
dagoof Avatar answered Oct 26 '22 23:10

dagoof