Benford's law: Difference between revisions

m
Line 1,979:
χ² = 3204.8072</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia"># fast Fibonacci number iteratorBenford's Law
P(d) = log10(1 + 1/d)
struct Fib end
Base.iterate(::Fib, (a, b) = (big(0), big(1))) = b, (b, a + b)
Base.eltype(::Type{Fib}) = BigInt
Base.IteratorSize(::Type{Fib}) = Base.IsInfinite()
fibs(n) = Iterators.take(Fib(), n)
 
function benford(listnumbers)
counts = zeros(Int, 9)
firstdigit(n) = parse(Int, first(string(n)))
counts = zeros(Int, 9)
countdigit(n) = counts[firstdigit(n)] += 1
foreach(countdigitn -> counts[firstdigit(n)] += 1, listnumbers)
counts ./ sum(counts)
end
 
struct FibFibonacci end
# Benford's law
Base.iterate(::FibFibonacci, (a, b) = (big.((0), big(1))) = b, (b, a + b)
P(d) = log10(1 + 1/d)
 
fibs(n)sample = Iterators.take(FibFibonacci(), n1000)
Real[1:9 benford(fibs(1000)) P.(1:9)]</syntaxhighlight>
 
observed = benford(sample) .* 100
expected = P.(1:9) .* 100
 
table = Real[1:9 observed expected]
 
using Plots
plot([observed expected]; title = "Benford's Law",
seriestype = [:bar :line], linewidth = [0 5],
xticks = 1:9, xlabel = "first digit", ylabel = "frequency %",
label = ["1000 Fibonacci numbers" "P(d)=log10(1+1/d)"])
using Printf
println("Benford's Law\nFrequency of first digit\nin 1000 Fibonacci numbers")
println("digit observed expected")
foreach(i -> @printf("%3d%9.2f%%%9.2f%%\n", table[i,:]...), 1:9)</syntaxhighlight>
{{Out}}
<pre>9×3Benford's Matrix{Real}:Law
Frequency of first digit
1 0.301 0.30103
in 1000 Fibonacci numbers
2 0.177 0.176091
digit observed expected
3 0.125 0.124939
4 01 30.09610% 030.0969110%
5 02 17.0870% 017.079181261%
6 03 12.06750% 012.066946849%
7 04 9.05660% 09.057991969%
8 05 8.05300% 07.051152592%
6 6.70% 6.69%
9 0.045 0.0457575</pre>
7 5.60% 5.80%
8 5.30% 5.12%
9 4.50% 4.58%</pre>
 
=={{header|Kotlin}}==
39

edits