+4 votes
in Programming Languages by (73.8k points)
I want to generate random probabilities for a data set. How can I create a list of float values between 0 and 1?

E.g.

y = [0.11, 0.89, 0.71, 0.56, 0.23, 0.45, 0.43, 0.60]

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

You can use functions of the Python module "random" to create a list of float values between 0 and 1.

  1. Using random(): It generates a random float value between 0 and 1.
  2. Using uniform(a,b): It generates a random float value between a and b. You can provide a=0 and b=1 in this function to get a float value between 0 and 1.

Here are examples using these functions:

>>> import random
>>> sample_size=10
>>> probs = [random.uniform(0,1) for _ in range(sample_size)]
>>> probs
[0.7175525829668389, 0.6537445452615875, 0.6205947788347753, 0.8814101701145837, 0.39500224425887587, 0.6408448561857533, 0.37409569130670406, 0.2532876028548633, 0.740000480530124, 0.08745876946577569]

>>> probs = [random.random() for _ in range(sample_size)]
>>> probs
[0.09488058562632118, 0.42418533264241065, 0.6371554861986573, 0.5407210405371454, 0.8250288956912062, 0.6047729292581973, 0.4421300682424716, 0.31070523748147183, 0.3032950891802346, 0.3189890786841326]


...