Benford's law: Difference between revisions

m
Line 1,979:
χ² = 3204.8072</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">using# BenchmarkTools,fast Fibonacci number iterator Printf
 
# fast Fibonacci number iterator
struct Fib end
Base.iterate(::Fib, (a, b) = (big(10), big(1))) = ab, (b, a + b)
Base.eltype(::Type{Fib}) = BigInt
Base.IteratorSize(::Type{Fib}) = Base.IsInfinite()
fibfibs(n) = Iterators.take(Fib(), n)
 
function benford(list)
# relative frequency of first digits in a list of numbers
function benford_freq(list)
counts = zeros(Int, 9)
foreachfirstdigit(n) ->= counts[parse(Int, first(string(n)))] += 1, list)
countdigit(n) = counts[firstdigit(n)] += 1
foreach(countdigit, list)
counts ./ sum(counts)
end
 
# Benford's law
@btime benford_freq(fib(1000))
P(d) = log10(1 + 1 / d)
 
Real[1:9 benford(fibfibs(1000)) P.(1:9)]</syntaxhighlight>
# Benfords law
P(d) = log10(1 + 1 / d)
 
# compare a list of numbers to Benfords law (pretty printing)
function benford(list)
println("\nd Freq(d) P(d)")
for (d, a) ∈ enumerate(benford_freq(list))
comp(a, b) = isapprox(a, b, atol = 1e-2) ? "≈" : "≉"
b = P(d)
@printf "%d: %.5f %s %.5f \n" d a comp(a, b) b
end
end
 
benford(fib(1000))</syntaxhighlight>
{{Out}}
<pre>9×3 Matrix{Real}:
<pre> 413.400 μs (6695 allocations: 337.42 KiB)
1 0.301 0.30103
 
2 0.177 0.176091
d Freq(d) P(d)
1: 3 0.30100125 0.30103124939
2: 4 0.17700096 0.1760909691
3: 5 0.1250008 0.124940791812
4: 6 0.09600067 0.09691 0669468
5: 7 0.08000056 0.079180579919
6: 8 0.06700053 0.066950511525</pre>
7: 0.05600 ≈ 0.05799
8: 0.05300 ≈ 0.05115
9: 0.04500 ≈ 0.04576
</pre>
 
=={{header|Kotlin}}==
39

edits