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)]
CodePudding user response:
Because logarithm and exponential are inverse functions of eachother, you can do that by generating a number along a uniform distribution, and then compute its exponential
import numpy as np
N = 100
x = 10 ** np.random.uniform(low=-307, high=309, size=N)
keep in mind that the resulting distribution will not be uniform (because it is "distorted" by the exponential). Very often, the sample will be very close to 0 or very close to infinity.