Benford's law: Difference between revisions

Content added Content deleted
Line 1,979: Line 1,979:
χ² = 3204.8072</pre>
χ² = 3204.8072</pre>
=={{header|Julia}}==
=={{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}}
{{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 0.177 0.176091
1: 0.30100 0.30103
3 0.125 0.124939
2: 0.17700 0.17609
4 0.096 0.09691
3: 0.12500 0.12494
5 0.08 0.0791812
4: 0.09600 0.09691
6 0.067 0.0669468
5: 0.08000 0.07918
7 0.056 0.0579919
6: 0.06700 0.06695
8 0.053 0.0511525
7: 0.05600 0.05799
9 0.045 0.0457575
8: 0.05300 0.05115
9: 0.04500 ≈ 0.04576
</pre>
</pre>

=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">import java.math.BigInteger
<syntaxhighlight lang="scala">import java.math.BigInteger