Benford's law: Difference between revisions

Add ABC
(Add ABC)
 
(19 intermediate revisions by 10 users not shown)
Line 156:
9: 4.50% | 4.58% | 0.0757%
</pre>
=={{header|ABC}}==
<syntaxhighlight lang="abc">HOW TO RETURN fibonacci.numbers n:
PUT 1, 1 IN a, b
PUT {} IN fibo
FOR i IN {1..n}:
INSERT a IN fibo
PUT b, a+b IN a, b
RETURN fibo
 
HOW TO RETURN digit.distribution nums:
PUT {} IN digits
FOR i IN {1..9}: PUT i IN digits["`i`"]
PUT {} IN dist
FOR i IN {1..9}: PUT 0 IN dist[i]
FOR n IN nums:
PUT digits["`n`"|1] IN digit
PUT dist[digit] + 1 IN dist[digit]
FOR i IN {1..9}:
PUT dist[i] / #nums IN dist[i]
RETURN dist
 
PUT digit.distribution fibonacci.numbers 1000 IN observations
 
WRITE "Digit"<<6, "Expected">>10, "Observed">>10/
FOR d IN {1..9}:
WRITE d<<6, ((10 log (1 + 1/d))>>10)|10, observations[d]>>10/</syntaxhighlight>
{{out}}
<pre>Digit Expected Observed
1 0.30102999 0.301
2 0.17609125 0.177
3 0.12493873 0.125
4 0.09691001 0.096
5 0.07918124 0.08
6 0.06694678 0.067
7 0.05799194 0.056
8 0.05115252 0.053
9 0.04575749 0.045</pre>
 
=={{header|Ada}}==
 
Line 247 ⟶ 285:
8 1003 490.7 10.46 5.12 5.34
9 1006 438.9 10.49 4.58 5.91</pre>
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">text
Line 403 ⟶ 442:
Benford: 0.046 actual: 0.045
</pre>
 
=={{header|APL}}==
{{works with|Dyalog APL}}
<syntaxhighlight lang="apl">task←{
benf ← ≢÷⍨(⍳9)(+/∘.=)(⍎⊃∘⍕)¨
 
fibs ← (⊢,(+/¯2↑⊢))⍣998⊢1 1
 
exp ← 10⍟1+÷⍳9
obs ← benf fibs
 
⎕←'Expected Actual'⍪5⍕exp,[1.5]obs
}</syntaxhighlight>
{{out}}
<pre>Expected Actual
0.30103 0.30100
0.17609 0.17700
0.12494 0.12500
0.09691 0.09600
0.07918 0.08000
0.06695 0.06700
0.05799 0.05600
0.05115 0.05300
0.04576 0.04500</pre>
 
=={{header|Arturo}}==
Line 594 ⟶ 657:
9 0.045 0.046
</pre>
 
=={{header|BASIC256}}==
<syntaxhighlight lang="vb">n = 1000
dim actual(n) fill 0
 
for nr = 1 to n
num$ = string(fibonacci(nr))
j = int(left(num$,1))
actual[j] += 1
next
 
print "First 1000 Fibonacci numbers"
print "Digit ", "Actual freq ", "Expected freq"
for i = 1 to 9
freq = frequency(i)*100
print " "; ljust(i,4), rjust(actual[i]/10,5), rjust(freq,5)
next
end
 
function frequency(n)
return (log10(n+1) - log10(n))
end function
 
function fibonacci(f)
f = int(f)
a = 0 : b = 1 : c = 0 : n = 0
 
while n < f
a = b
b = c
c = a + b
n += 1
end while
 
return c
end function</syntaxhighlight>
{{Out}}
<pre>First 1000 Fibonacci numbers
Digit Actual freq Expected freq
1 30.1 30.1029995664
2 17.7 17.6091259056
3 12.5 12.4938736608
4 9.6 9.69100130081
5 8.0 7.91812460476
6 6.7 6.694679
7 5.6 5.79919469777
8 5.3 5.11525224474
9 4.5 4.57574905607</pre>
 
=={{header|C}}==
<syntaxhighlight lang="c">#include <stdio.h>
Line 749 ⟶ 861:
9 : 4.5 % 4.58 %
</pre>
 
=={{header|Chipmunk Basic}}==
{{trans|Yabasic}}
{{works with|Chipmunk Basic|3.6.4}}
<syntaxhighlight lang="vbnet">100 cls
110 n = 1000
120 dim actual(n)
130 for nr = 1 to n
140 num$ = str$(fibonacci(nr))
150 j = val(left$(num$,1))
160 actual(j) = actual(j)+1
170 next
180 print "First 1000 Fibonacci numbers"
190 print "Digit Actual freq Expected freq"
200 for i = 1 to 9
210 freq = frequency(i)*100
220 print format$(i,"###");
230 print using " ##.###";actual(i)/10;
240 print using " ##.###";freq
250 next
260 end
270 sub frequency(n)
280 frequency = (log10(n+1)-log10(n))
290 end sub
300 sub log10(n)
310 log10 = log(n)/log(10)
320 end sub
330 sub fibonacci(n)
335 rem https://rosettacode.org/wiki/Fibonacci_sequence#Chipmunk_Basic
340 n1 = 0
350 n2 = 1
360 for k = 1 to abs(n)
370 sum = n1+n2
380 n1 = n2
390 n2 = sum
400 next k
410 if n < 0 then
420 fibonacci = n1*((-1)^((-n)+1))
430 else
440 fibonacci = n1
450 endif
460 end sub</syntaxhighlight>
 
=={{header|Clojure}}==
<syntaxhighlight lang="lisp">(ns example
Line 1,089 ⟶ 1,244:
}</syntaxhighlight>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/[Benford%27s_law's law#Pascal |Pascal]].
 
=={{header|EasyLang}}==
<syntaxhighlight lang=easylang>
func$ add a$ b$ .
for i to higher len a$ len b$
a = number substr a$ i 1
b = number substr b$ i 1
r = a + b + c
c = r div 10
r$ &= r mod 10
.
if c > 0
r$ &= c
.
return r$
.
#
len fibdist[] 9
proc mkfibdist . .
# generate 1000 fibonacci numbers as
# (reversed) strings, because 53 bit
# integers are too small
#
n = 1000
prev$ = 0
val$ = 1
fibdist[1] = 1
for i = 2 to n
h$ = add prev$ val$
prev$ = val$
val$ = h$
ind = number substr val$ len val$ 1
fibdist[ind] += 1
.
for i to len fibdist[]
fibdist[i] = fibdist[i] / n
.
.
mkfibdist
#
len benfdist[] 9
proc mkbenfdist . .
for i to 9
benfdist[i] = log10 (1 + 1.0 / i)
.
.
mkbenfdist
#
numfmt 3 0
print "Actual Expected"
for i to 9
print fibdist[i] & " " & benfdist[i]
.
</syntaxhighlight>
{{out}}
<pre>
Actual Expected
0.301 0.301
0.177 0.176
0.125 0.125
0.096 0.097
0.080 0.079
0.067 0.067
0.056 0.058
0.053 0.051
0.045 0.046
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Benfords_law do
Line 1,123 ⟶ 1,346:
9 0.045 0.04575749056067514
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
Line 1,506 ⟶ 1,730:
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Benford%27s_law}}
 
'''Solution:'''
 
The following function calculates the distribution of the first digit of a list of integer, positive numbers:
 
[[File:Fōrmulæ - Benford's law 01.png]]
 
'''Example:'''
 
[[File:Fōrmulæ - Benford's law 02.png]]
 
[[File:Fōrmulæ - Benford's law 03.png]]
 
'''Benford distribution.''' Benford distribution is, by definition (using a precision of 10 digits):
 
[[File:Fōrmulæ - Benford's law 04.png]]
 
[[File:Fōrmulæ - Benford's law 05.png]]
 
'''Comparison chart.''' The following function creates a chart, in order to compare the distribution of the first digis in a givel list or numbers, and the Benford distribution:
 
[[File:Fōrmulæ - Benford's law 06.png]]
 
'''Testing.''' Testing with the previous list of numbers:
 
[[File:Fōrmulæ - Benford's law 07.png]]
 
[[File:Fōrmulæ - Benford's law 08.png]]
 
'''Case 1.''' Use the first 1,000 numbers from the Fibonacci sequence as your data set
 
[[File:Fōrmulæ - Benford's law 09.png]]
 
[[File:Fōrmulæ - Benford's law 10.png]]
 
'''Case 2.''' The sequence of the fisrt 1,000 natural numbers does not follow the Benford distribution:
 
[[File:Fōrmulæ - Benford's law 11.png]]
 
[[File:Fōrmulæ - Benford's law 12.png]]
 
'''Case 3.''' The following example is for the list of the fist 1,000 factorial numbers.
 
[[File:Fōrmulæ - Benford's law 13.png]]
 
[[File:Fōrmulæ - Benford's law 14.png]]
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
 
Short t, i, j, k, m
Double a(9), z
Double phi, psi
CFStringRef s
 
print @"Benford:"
for i = 1 to 9
a(i) = log10( 1 + 1 / i )
print fn StringWithFormat( @"%.3f ", a(i) ),
next
 
 
// Fibonacci according to DeMoivre and Binet
for t = 1 to 9 : a(t) = 0 : next // Clean array
phi = ( 1 + sqr(5) ) / 2
psi = ( 1 - sqr(5) ) / 2
for i = 1 to 1000
z = ( phi^i - psi^i ) / sqr( 5 )
s = fn StringWithFormat( @"%e", z) // Get first digit
t = fn StringIntegerValue( left( s, 1 ) )
a(t) = a(t) + 1
next
print @"\n\nFibonacci:"
for i = 1 to 9
print fn StringWithFormat( @"%.3f ", a(i) / 1000 ),
next
 
 
// Multiplication tables
for t = 1 to 9 : a(t) = 0 : next // Clean array
for i = 1 to 10
for j = 1 to 10
for k = 1 to 10
for m = 1 to 10
z = i * j * k * m
s = fn StringWithFormat( @"%e", z )
t = fn StringIntegerValue( left( s, 1 ) )
a(t) = a(t) + 1
next
next
next
next
print @"\n\nMultiplication:"
for i = 1 to 9
print fn StringWithFormat( @"%.3f ", a(i) / 1e4 ),
next
 
 
// Factorials according to DeMoivre and Stirling
for t = 1 to 9 : a(t) = 0 : next // Clean array
for i = 10 to 110
z = sqr(2 * pi * i ) * (i / exp(1) )^i
s = fn StringWithFormat( @"%e", z )
t = fn StringIntegerValue( left( s, 1 ) )
a(t) = a(t) + 1
next
print @"\n\nFactorials:"
for i = 1 to 9
print fn StringWithFormat( @"%.2f ", a(i) / 100 ),
next
 
 
handleevents
}</syntaxhighlight>
{{Out}}
<pre>
Benford:
0.301 0.176 0.125 0.097 0.079 0.067 0.058 0.051 0.046
 
Fibonacci:
0.301 0.177 0.125 0.096 0.080 0.067 0.056 0.053 0.045
 
Multiplication:
0.302 0.181 0.124 0.103 0.071 0.061 0.055 0.055 0.047
 
Factorials:
0.35 0.16 0.12 0.06 0.06 0.06 0.02 0.10 0.08
</pre>
 
 
=={{header|Go}}==
Line 2,015 ⟶ 2,368:
 
function benford(numbers)
firstdigit(n) = parselast(Int, first(stringdigits(n)))
counts = zeros(9)
foreach(n -> counts[firstdigit(n)] += 1, numbers)
Line 2,196 ⟶ 2,549:
8 0.053 0.0511525
9 0.045 0.0457575</pre>
 
=={{header|MATLAB}}==
{{trans|Julia}}
<syntaxhighlight lang="MATLAB">
benfords_law();
 
function benfords_law
% Benford's Law
P = @(d) log10(1 + 1./d);
 
% Benford function
function counts = benford(numbers)
firstdigit = @(n) floor(mod(n / 10^floor(log10(n)), 10));
counts = zeros(1, 9);
for i = 1:length(numbers)
digit = firstdigit(numbers(i));
if digit ~= 0
counts(digit) = counts(digit) + 1;
end
end
counts = counts ./ sum(counts);
end
 
% Generate Fibonacci numbers
function fibNums = fibonacci(n)
fibNums = zeros(1, n);
a = 0;
b = 1;
for i = 1:n
c = b;
b = a + b;
a = c;
fibNums(i) = b;
end
end
 
% Sample
sample = fibonacci(1000);
 
% Observed and expected frequencies
observed = benford(sample) * 100;
expected = arrayfun(P, 1:9) * 100;
 
% Table
mytable = [1:9; observed; expected]';
 
% Plotting
bar(1:9, observed);
hold on;
plot(1:9, expected, 'LineWidth', 2);
hold off;
title("Benford's Law");
xlabel("First Digit");
ylabel("Frequency %");
legend("1000 Fibonacci Numbers", "P(d) = log10(1 + 1/d)");
xticks(1:9);
 
% Displaying the results
fprintf("Benford's Law\nFrequency of first digit\nin 1000 Fibonacci numbers\n");
disp(table(mytable(:,1),mytable(:,2),mytable(:,3),'VariableNames',{'digit', 'observed(%)', 'expected(%)'}))
end
</syntaxhighlight>
{{out}}
<pre>
Benford's Law
Frequency of first digit
in 1000 Fibonacci numbers
digit observed(%) expected(%)
_____ ___________ ___________
 
1 30 30.103
2 17.7 17.609
3 12.5 12.494
4 9.6 9.691
5 8 7.9181
6 6.7 6.6947
7 5.7 5.7992
8 5.3 5.1153
9 4.5 4.5757
</pre>
 
 
=={{header|NetRexx}}==
<syntaxhighlight lang="netrexx">/* NetRexx */
Line 3,714 ⟶ 4,149:
8 0.05115 0.06646 0.01531
9 0.04576 0.05831 0.01255</pre>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program benfords_law;
fibos := fibo_list(1000);
 
expected := [log(1 + 1/d)/log 10 : d in [1..9]];
actual := benford(fibos);
 
print('d Expected Actual');
loop for d in [1..9] do
print(d, ' ', fixed(expected(d), 7, 5), ' ', fixed(actual(d), 7, 5));
end loop;
 
proc benford(list);
dist := [];
loop for n in list do
dist(val(str n)(1)) +:= 1;
end loop;
return [d / #list : d in dist];
end proc;
 
proc fibo_list(n);
a := 1;
b := 1;
fibs := [];
loop while n>0 do
fibs with:= a;
[a, b] := [b, a+b];
n -:= 1;
end loop;
return fibs;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre>d Expected Actual
1 0.30103 0.30100
2 0.17609 0.17700
3 0.12494 0.12500
4 0.09691 0.09600
5 0.07918 0.08000
6 0.06695 0.06700
7 0.05799 0.05600
8 0.05115 0.05300
9 0.04576 0.04500</pre>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var (actuals, expected) = ([], [])
var fibonacci = 1000.of {|i| fib(i).digit(0-1) }
 
for i in (1..9) {
var num = fibonacci.count_by {|j| j == i }
actuals.append(num / 1000)
Line 3,725 ⟶ 4,204:
 
"%17s%17s\n".printf("Observed","Expected")
 
for i (1..9) {
for i in (1..9) {
"%d : %11s %%%15s %%\n".printf(
i, "%.2f".sprintf(100 * actuals[i - 1]),
Line 3,731 ⟶ 4,211:
)
}</syntaxhighlight>
 
{{out}}
<pre>
Line 3,745 ⟶ 4,224:
9 : 4.50 % 4.58 %
</pre>
 
=={{header|SQL}}==
If we load some numbers into a table, we can do the sums without too much difficulty. I tried to make this as database-neutral as possible, but I only had Oracle handy to test it on.
Line 4,048 ⟶ 4,528:
9 | 4.50% | 4.58%
</pre>
 
=={{header|True BASIC}}==
{{trans|Chipmunk Basic}}
<syntaxhighlight lang="qbasic">FUNCTION log10(n)
LET log10 = LOG(n)/LOG(10)
END FUNCTION
 
FUNCTION frequency(n)
LET frequency = (log10(n+1)-log10(n))
END FUNCTION
 
FUNCTION fibonacci(n)
!https://rosettacode.org/wiki/Fibonacci_sequence#True_BASIC
LET n1 = 0
LET n2 = 1
FOR k = 1 TO ABS(n)
LET sum = n1+n2
LET n1 = n2
LET n2 = sum
NEXT k
IF n < 0 THEN LET fibonacci = n1*((-1)^((-n)+1)) ELSE LET fibonacci = n1
END FUNCTION
 
CLEAR
LET n = 1000
DIM actual(0)
MAT REDIM actual(n)
FOR nr = 1 TO n
LET num$ = STR$(fibonacci(nr))
LET j = VAL((num$)[1:1])
LET actual(j) = actual(j)+1
NEXT nr
PRINT "First 1000 Fibonacci numbers"
PRINT "Digit Actual freq Expected freq"
FOR i = 1 TO 9
LET freq = frequency(i)*100
PRINT USING "###": i;
PRINT USING " ##.###": actual(i)/10;
PRINT USING " ##.###": freq
NEXT i
END</syntaxhighlight>
 
=={{header|VBA (Visual Basic for Application)}}==
<syntaxhighlight lang="vb">
Line 4,187 ⟶ 4,709:
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascriptwren">import "./fmt" for Fmt
 
var fib1000 = Fn.new {
Line 4,276 ⟶ 4,798:
9 0.04500 0.04576 0.00076
</pre>
 
=={{header|Yabasic}}==
Using function from https://www.rosettacode.org/wiki/Fibonacci_sequence#Yabasic
<syntaxhighlight lang="vb">n = 1000
dim actual(n)
 
for nr = 1 to n
num$ = str$(fibonacci(nr))
j = val(left$(num$,1))
actual(j) = actual(j) + 1
next
 
print "First 1000 Fibonacci numbers"
print "Digit ", "Actual freq ", "Expected freq"
for i = 1 to 9
freq = frequency(i)*100
print i using("###"), " ", (actual(i)/10) using("##.###"), " ", freq using("##.###")
next
end
 
sub frequency(n)
return (log10(n+1) - log10(n))
end sub
 
sub log10(n)
return log(n) / log(10)
end sub
sub fibonacci(n)
local n1, n2, k, sum
n1 = 0
n2 = 1
for k = 1 to abs(n)
sum = n1 + n2
n1 = n2
n2 = sum
next k
if n < 0 then
return n1 * ((-1) ^ ((-n) + 1))
else
return n1
end if
end sub</syntaxhighlight>
{{out}}
<pre>First 1000 Fibonacci numbers
Digit Actual freq Expected freq
1 30.100 30.103
2 17.700 17.609
3 12.500 12.494
4 9.600 9.691
5 8.000 7.918
6 6.700 6.695
7 5.600 5.799
8 5.300 5.115
9 4.500 4.576</pre>
 
=={{header|zkl}}==
2,093

edits