Skip to content

Instantly share code, notes, and snippets.

@wteuber
Last active September 20, 2021 15:29
Show Gist options
  • Save wteuber/6e30b658e0a36b3b7258e22c019ddfed to your computer and use it in GitHub Desktop.
Save wteuber/6e30b658e0a36b3b7258e22c019ddfed to your computer and use it in GitHub Desktop.
Random number generator with Benford's law distribution, fmi see https://en.wikipedia.org/wiki/Benford%27s_law and https://rosettacode.org/wiki/Benford%27s_law#Ruby
r=rand;(1..9).map{|n|Math.log10(1+1.0/n)}.inject([]){|a,e|a+[(a[-1]||0)+e]}.map.with_index{|p,i|[i+1,p]}.find{r<_2}[0]
100000.times.map{r=rand;(1..9).map{|n|Math.log10(1+1.0/n)}.inject([]){|a,e|a+[(a[-1]||0)+e]}.map.with_index{|p,i|[i+1,p]}.find{r<_2}[0]}.inject(Hash.new(0)) { |total, e| total[e] += 1 ;total}.sort_by(&:last)
# => [[9, 4535], [8, 5072], [7, 5932], [6, 6743], [5, 7801], [4, 9702], [3, 12667], [2, 17494], [1, 30054]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment