lundi 31 mai 2021

How to make Python random.randrange more efficient to generate large range random number

Code to generate random integer

for i in range(10):
   count = 0
   dict = {}

   while count < 10000000:
      rnd = random.randrange(0, 7800000000)
      rndlen = len(str(rnd))
      if rndlen in dict:
         dict[rndlen] += 1
      else:
         dict[rndlen] = 1
      count += 1
        
   print(dict)

Results generated

{10: 8717806, 9: 1154071, 8: 115280, 6: 1133, 7: 11573, 5: 122, 4: 14, 3: 1}
{10: 8717846, 9: 1153444, 8: 115856, 7: 11615, 6: 1122, 5: 110, 4: 5, 3: 1, 2: 1}
{10: 8718446, 9: 1153425, 8: 115151, 7: 11667, 6: 1201, 5: 101, 4: 9}
{10: 8717658, 9: 1153838, 7: 11581, 8: 115641, 5: 114, 6: 1156, 4: 11, 3: 1}
{9: 1153775, 10: 8717832, 8: 115572, 7: 11556, 6: 1134, 5: 121, 4: 9, 3: 1}
{10: 8718564, 9: 1153704, 8: 115002, 7: 11498, 6: 1115, 5: 105, 4: 11, 3: 1}
{10: 8718322, 9: 1153617, 8: 115128, 7: 11590, 6: 1217, 5: 115, 4: 11}
{10: 8718181, 9: 1153681, 7: 11554, 8: 115270, 6: 1177, 5: 128, 4: 8, 3: 1}
{9: 1151777, 10: 8720590, 8: 115017, 7: 11333, 6: 1159, 5: 113, 4: 10, 3: 1}
{10: 8717127, 9: 1154596, 8: 115344, 7: 11591, 6: 1230, 5: 100, 4: 11, 3: 1}

The results show that the random integer generated more toward the max value instead of min value, ~87% on max value, less than 1% is near to min value.

How to solve this issue to generate a fair random range?




Aucun commentaire:

Enregistrer un commentaire