0

I'm not very good with python and I need to create a function, randvec(n), that will create an n-dimensional vector where each element is a random real number in [0,100). Below is what I have so far.

def randvec(n):
    vector = np.ndarray((1,n),dtype=float)
    for i in range(0,n):
        vector[i] = np.random.uniform(0,100)
        print(vector[i])

test = randvec(4)
print(test)

Output: [64.58722344 64.58722344 64.58722344 64.58722344]

Based on the outputs when I print inside the for loop, I don't think random.uniform() is the function I want to use because it gives me the same random number n times.

I also get this error message "index 1 is out of bounds for axis 0 with size 1."

Let me know if you see my mistakes! Thanks

Tom Zych
  • 13,329
  • 9
  • 36
  • 53
nicons
  • 13
  • 4
  • "it gives me the same random number n times" - no way, please post a [mcve] – ForceBru Mar 14 '20 at 16:46
  • I edited with the print inside the for loop and provided the output. Hope that's what you meant and that it helps – nicons Mar 14 '20 at 16:57
  • Please provide the entire error message. Why not use the appropriate NumPy function(s) for this? – AMC Mar 14 '20 at 20:11

1 Answers1

0
def randvec(n):
   return [random.random()*100 for _ in range(n)]

will generate n real random values such that each value is in interval [0, 100). See class Random for more information on random() method.

But that's a PRNG (pseudo random number generator) meaning that it is predictable the "random" sequence. From Documentation:

Warning: The pseudo-random generators of this module should not be used for security purposes. Use os.urandom() or SystemRandom if you require a cryptographically secure pseudo-random number generator.

For security purposes use a TRNG or CSPRNGs.

  • Thanks! I'm not sure why I didn't think of something this simple. Maybe not good enough for security but good enough for my math homework. – nicons Mar 14 '20 at 17:05