Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating list of random numbers in python

I have initiated a list of known length with zeros. I am trying to go back through the list and put random floating point numbers from 0-1 at each index. I am using a while loop to do this. However, the code is not putting the random numbers in. The list is still full of zeros and I do not understand why. I've inserted a print statement which is telling me the list is still full of zeros. I would appreciate any help!

randomList = [0]*10
index = 0
while index < 10:
    randomList[index] = random.random()
    print("%d" %randomList[index])
    index = index + 1
like image 660
JP1992 Avatar asked Dec 09 '22 10:12

JP1992


1 Answers

List is random:

>>> randomList
[0.46044625854330556, 0.7259964854084655, 0.23337439854506958, 0.4510862027107614, 0.5306153865653811, 0.8419679084235715, 0.8742117729328253, 0.7634456118593921, 0.5953545552492302, 0.7763910850561638]

But you print it's elements as itegers with "%d" % randomList[index], so all those values are rounded to zero. You can use "%f" formatter to print float numbers:

>>> print("%.5f" % randomList[index])
0.77639

or '{:M:Nf}.format':

>>> print("{.5f}".format(randomList[index]))
0.77639   
like image 132
alko Avatar answered Dec 15 '22 00:12

alko