Benford's law: Difference between revisions

Line 1,979:
χ² = 3204.8072</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">using BenchmarkTools, Printf
 
# fast Fibonacci number iterator
<syntaxhighlight lang="julia">fib(n) = ([one(n) one(n) ; one(n) zero(n)]^n)[1,2]
struct Fib end
Base.iterate(::Fib, (a, b) = (big(1), big(1))) = a, (b, a + b)
Base.eltype(::Type{Fib}) = BigInt
Base.IteratorSize(::Type{Fib}) = Base.IsInfinite()
fib(n) = Iterators.take(Fib(), n)
 
# relative frequency of first digits in a list of numbers
ben(l) = [count(x->x==i, map(n->string(n)[1],l)) for i='1':'9']./length(l)
function benford_freq(list)
counts = zeros(Int, 9)
foreach(n -> counts[parse(Int, first(string(n)))] += 1, list)
counts ./ sum(counts)
end
 
@btime benford_freq(fib(1000))
benford(l) = [Number[1:9;] ben(l) log10(1.+1./[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> 413.400 μs (6695 allocations: 337.42 KiB)
<pre>julia> benford([fib(big(n)) for n = 1:1000])
 
9x3 Array{Number,2}:
d Freq(d) P(d)
1 0.301 0.30103
2 1: 0.17730100 0.176091 30103
3 2: 0.12517700 0.124939 17609
4 3: 0.09612500 0.09691 12494
5 4: 0.08 09600 0.079181209691
6 5: 0.06708000 0.066946807918
7 6: 0.05606700 0.057991906695
8 7: 0.05305600 0.051152505799
9 8: 0.04505300 0.045757505115
9: 0.04500 ≈ 0.04576
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">import java.math.BigInteger
39

edits