Reputation: 487
Goals: to Initialize an array with pre-defined size with a random number. I have try this way and working:
xa = np.empty(100)
xa[0] = random.random()
for i in range(1,100):
xa[i] = xa[i-1] + random.random()
My question: Is there any better way to do it? maybe without the for loop?
Upvotes: 2
Views: 5561
Reputation: 61910
Given that you are using numpy the code in your question is equivalent to:
import numpy as np
np.random.seed(42)
xa = np.cumsum(np.random.random(100))
print(xa[:5])
Output
[0.37454012 1.32525443 2.05724837 2.65590685 2.81192549]
But if what you want if something that returns a range (like the one from the range function), but with a random step you could do something like this:
xa = np.cumsum(np.random.randint(100, size=(100,)))
print(xa[:5])
Output
[ 62 157 208 303 306]
Note that in both cases only the first 5 numbers are printed. Also in both cases the step is positive.
Further
Upvotes: 1
Reputation: 13858
Use list comprehension:
import random
n = 100 # your array size
xa = [random.random() for _ in range(n)]
Again as mentioned, np.empty(100)
would already give you a fully random array of the size. What is the issue with np.empty()
?
Upvotes: 0
Reputation: 357
Simple one-liner
import random
xa = random.sample(range(1, 101), 100)
Upvotes: 2
Reputation: 23484
You also can use itertools.accumulate
function:
from itertools import accumulate
import numpy as np
import random
xa = np.empty(100)
xa[0] = random.random()
xa = list(accumulate(xa, lambda x, y: x + random.random()))
I am not quite sure that this is what you need, but it computes every element with prev + random.random()
like you wrote in your question.
Upvotes: 1
Reputation: 90
you can use this better than your code
import random
xa = [None] * 100
xa[0] = random.random()
for i in xrange(1, 100):
xa[i] = xa[i-1] + random.random()
Upvotes: 0