mardi 24 mai 2022

How to generate a random number in the entire binary64 range

I am wondering how to generate a random double number inside the entire double range in Python, so that the order of magnitude of the number (math.log10) has an equal chance to be any of the possible magnitudes (range(-307, 309)).

I tried the following code but it does not give intended result:

from random import random, uniform
from collections import Counter
import math
import sys

random_numbers = [random()/random() for i in range(2048)]

count = Counter([int(math.log10(i)) for i in random_numbers])

print(count.most_common())

uniform_numbers = [uniform(sys.float_info.min, sys.float_info.max) for i in range(2048)]

count1 = Counter([int(math.log10(i)) for i in uniform_numbers])

print(count1.most_common())
[(0, 1862), (1, 93), (-1, 68), (2, 14), (-2, 10), (3, 1)] 
[(307, 1055), (308, 888), (306, 95), (305, 10)]



Aucun commentaire:

Enregistrer un commentaire