tags:

views:

183

answers:

2

Hi all, 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

+1  A: 

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]=???
dagoof
+2  A: 

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(100) # Set the random nymber generator to a fixed sequence.
r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)])
Simon Callan
thanks for answering, great help!however I dont quite understand what is that 100 mean?
Oddly enough, the `100` is just a random number. To ensure that the `random` functions return the same sequence, you need to pass in the same value to `seed()` each time, but the actual value itself is irrelevant. 100 just happened to be the first one that came to mind.If I'd been thinking more, I'd probably have gone for 42.
Simon Callan