user211037
user211037

Reputation: 1855

How to fix value produced by 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

Upvotes: 7

Views: 25911

Answers (2)

Simon Callan
Simon Callan

Reputation: 3130

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)])

Upvotes: 21

dagoof
dagoof

Reputation: 1139

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]=???

Upvotes: 1

Related Questions