Python has a number of ways to generate different distributions of random numbers, see the documentation for the random
module. Unfortunately they aren't terribly understandable without the appropriate math background, especially considering the required parameters.
I'd like to know if any of those methods are capable of producing random numbers with a distribution that obeys Benford's Law, and what parameter values are appropriate. Namely for a population of integers, those integers should start with a '1' about 30% of the time, '2' about 18% of the time, etc.
Using Jan Dvorak's answer I put together the following code, and it appears to work perfectly.
def benfords_range_gen(stop, n):
""" A generator that returns n random integers
between 1 and stop-1 and whose distribution
meets Benford's Law i.e. is logarithmic.
"""
multiplier = math.log(stop)
for i in range(n):
yield int(math.exp(multiplier * random.random()))
>>> from collections import Counter
>>> Counter(str(i)[0] for i in benfords_range_gen(10000, 1000000))
Counter({'1': 300696, '2': 176142, '3': 124577, '4': 96756, '5': 79260, '6': 67413, '7': 58052, '8': 51308, '9': 45796})