如何生成整个binary64范围内的随机数
How to generate a random number in the entire binary64 range
我想知道如何在Python的整个double范围内生成一个随机double数,以便数字的数量级(math.log10
)有相同的机会是任何可能的震级 (range(-307, 309)
).
我尝试了以下代码,但没有给出预期的结果:
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)]
因为对数和指数是互为反函数,所以您可以生成一个服从均匀分布的数,然后计算它的指数
import numpy as np
N = 100
x = 10 ** np.random.uniform(low=-307, high=309, size=N)
请记住,生成的分布将不是均匀的(因为它被指数“扭曲”了)。很多时候,样本会非常接近 0 或非常接近无穷大。
我想知道如何在Python的整个double范围内生成一个随机double数,以便数字的数量级(math.log10
)有相同的机会是任何可能的震级 (range(-307, 309)
).
我尝试了以下代码,但没有给出预期的结果:
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)]
因为对数和指数是互为反函数,所以您可以生成一个服从均匀分布的数,然后计算它的指数
import numpy as np
N = 100
x = 10 ** np.random.uniform(low=-307, high=309, size=N)
请记住,生成的分布将不是均匀的(因为它被指数“扭曲”了)。很多时候,样本会非常接近 0 或非常接近无穷大。