Benford's law: Difference between revisions
→{{header|Julia}}
Line 1,979:
χ² = 3204.8072</pre>
=={{header|Julia}}==
<syntaxhighlight lang="julia">using BenchmarkTools, Printf
# fast Fibonacci number iterator
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
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))
# 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)
d Freq(d) P(d)
9: 0.04500 ≈ 0.04576
</pre>
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">import java.math.BigInteger
|