Is there a random number distribution that obeys Benford's Law?

北慕城南 提交于 2019-12-01 15:59:49

Benford's law describes the distribution of the first digits of a set of numbers if the numbers are chosen from a wide range on the logarithmic scale. If you prepare a log-uniform distribution over one decade, it will respect the law as well. 10^[0,1) will produce that distribution.

This will produce the desired distribution: math.floor(10**random.random())

Just playing around.

A much more inefficient, but perhaps more visible implementation for those, like myself, who are not so math inclined...

An easy way to create any desired distribution is to fill a list with the desired percentages of an item, and then use random.choice(<list>), since this returns a uniform selection of items in the list.

import random
probs = [30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6]
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
population = sum([[n] * int(p * 10) for n, p in zip(nums, probs)], [])

max_value = 100
min_value = 1
result_pop = []
target_pop_size = 1000
while len(result_pop) < target_pop_size:
    s = str(random.choice(population))
    while True:
        r = random.randint(min_value, max_value)
        if str(r).startswith(s):
            break
    result_pop.append(r)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!