Benford's law: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 34:
=={{header|11l}}==
{{trans|D}}
<langsyntaxhighlight lang=11l>F get_fibs()
V a = 1.0
V b = 1.0
Line 58:
 
L(p) benford(get_fibs())
print(‘#.: #2.2% | #2.2% | #.4%’.format(L.index + 1, p[1] * 100, p[0] * 100, abs(p[1] - p[0]) * 100))</langsyntaxhighlight>
{{out}}
<pre>
Line 74:
 
=={{header|8th}}==
<langsyntaxhighlight lang=8th>
: n:log10e ` 1 10 ln / ` ;
 
Line 142:
benford-test
bye
</syntaxhighlight>
</lang>
 
{{out}}
Line 162:
The program reads the Fibonacci-Numbers from the standard input. Each input line is supposed to hold N, followed by Fib(N).
 
<langsyntaxhighlight lang=Ada>with Ada.Text_IO, Ada.Numerics.Generic_Elementary_Functions;
 
procedure Benford is
Line 210:
Ada.Text_IO.New_Line;
end loop;
end Benford;</langsyntaxhighlight>
 
{{out}}
Line 230:
Input is the list of primes below 100,000 from [http://www.mathsisfun.com/numbers/prime-number-lists.html]. Since each line in that file holds prime and only a prime, but no ongoing counter, we must slightly modify the program by commenting out a single line:
 
<langsyntaxhighlight lang=Ada> -- N_IO.Get(Counter);</langsyntaxhighlight>
 
We can also edit out the declaration of the variable "Counter" ...or live with a compiler warning about never reading or assigning that variable.
Line 251:
 
=={{header|Aime}}==
<langsyntaxhighlight lang=aime>text
sum(text a, text b)
{
Line 338:
 
0;
}</langsyntaxhighlight>
{{out}}
<pre> expected found
Line 354:
{{works with|ALGOL 68G|Any - tested with release 2.8.3.win32}}
Uses Algol 68G's LONG LONG INT which has programmer specifiable precision.
<langsyntaxhighlight lang=algol68>BEGIN
# set the number of digits for LONG LONG INT values #
PR precision 256 PR
Line 390:
# compare to the probabilities expected by Benford's law #
compare to benford( digit probability( fn ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 406:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}(AutoHotkey1.1+)
<langsyntaxhighlight lang=AutoHotkey>SetBatchLines, -1
fib := NStepSequence(1, 1, 2, 1000)
Out := "Digit`tExpected`tObserved`tDeviation`n"
Line 448:
}
return, (Carry ? Carry : "") . Result
}</langsyntaxhighlight>NStepSequence() is available [http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences#AutoHotkey here].
'''Output:'''
<pre>Digit Expected Observed Deviation
Line 462:
 
=={{header|AWK}}==
<langsyntaxhighlight lang=AWK>
# syntax: GAWK -f BENFORDS_LAW.AWK
BEGIN {
Line 490:
function abs(x) { if (x >= 0) { return x } else { return -x } }
function log10(x) { return log(x)/log(10) }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 507:
=={{header|BCPL}}==
BCPL doesn't do floating point well, so I use integer math to compute the most significant digits of the Fibonacci sequence and use a table that has the values of log10(d + 1/d)
<langsyntaxhighlight lang=BCPL>
GET "libhdr"
 
Line 549:
RESULTIS 0
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 568:
 
=={{header|C}}==
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 631:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
{{Out}}
Line 648:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>//to cope with the big numbers , I used the Class Library for Numbers( CLN )
//if used prepackaged you can compile writing "g++ -std=c++11 -lcln yourprogram.cpp -o yourprogram"
#include <cln/integer.h>
Line 710:
return 0 ;
}
</syntaxhighlight>
</lang>
{{out}}
<pre> found expected
Line 725:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=lisp>(ns example
(:gen-class))
 
Line 799:
(show-benford-stats y))
 
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 838:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang=coffeescript>fibgen = () ->
a = 1; b = 0
return () ->
Line 858:
console.log "Digit\tActual\tExpected"
for i in [1..9]
console.log i + "\t" + actual[i - 1].toFixed(3) + '\t' + expected[i - 1].toFixed(3)</langsyntaxhighlight>
{{out}}
<pre>Leading digital distribution of the first 1,000 Fibonacci numbers
Line 873:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang=lisp>(defun calculate-distribution (numbers)
"Return the frequency distribution of the most significant nonzero
digits in the given list of numbers. The first element of the list
Line 915:
(map 'list #'list '(1 2 3 4 5 6 7 8 9)
actual-distribution
expected-distribution))))</langsyntaxhighlight>
 
<pre>; *fib1000* is a list containing the first 1000 numbers in the Fibonnaci sequence
Line 932:
=={{header|Crystal}}==
{{trans|Ruby}}
<langsyntaxhighlight lang=ruby>require "big"
 
EXPECTED = (1..9).map{ |d| Math.log10(1 + 1.0 / d) }
Line 970:
# just to show that not all kind-of-random sets behave like that
show_dist("random", random(10000))</langsyntaxhighlight>
 
{{out}}
Line 1,010:
=={{header|D}}==
{{trans|Scala}}
<langsyntaxhighlight lang=d>import std.stdio, std.range, std.math, std.conv, std.bigint;
 
double[2][9] benford(R)(R seq) if (isForwardRange!R && !isInfinite!R) {
Line 1,033:
writefln("%d: %5.2f%% | %5.2f%% | %5.4f%%",
i+1, p[1] * 100, p[0] * 100, abs(p[1] - p[0]) * 100);
}</langsyntaxhighlight>
{{out}}
<pre> Actual Expected Deviation
Line 1,049:
===Alternative Version===
The output is the same.
<langsyntaxhighlight lang=d>import std.stdio, std.range, std.math, std.conv, std.bigint,
std.algorithm, std.array;
 
Line 1,066:
f * 100.0 / N, expected[i] * 100,
abs((f / double(N)) - expected[i]) * 100);
}</langsyntaxhighlight>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Benford%27s_law#Pascal Pascal].
=={{header|Elixir}}==
<langsyntaxhighlight lang=elixir>defmodule Benfords_law do
def distribution(n), do: :math.log10( 1 + (1 / n) )
Line 1,087:
end
 
Benfords_law.task</langsyntaxhighlight>
 
{{out}}
Line 1,104:
 
=={{header|Erlang}}==
<langsyntaxhighlight lang=Erlang>
-module( benfords_law ).
-export( [actual_distribution/1, distribution/1, task/0] ).
Line 1,130:
[Key | _] = erlang:integer_to_list( N ),
dict:update_counter( Key - 48, 1, Dict ).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,150:
For Fibonacci code, see https://rosettacode.org/wiki/Fibonacci_sequence#F.89
 
<langsyntaxhighlight lang=fsharp>open System
 
let fibonacci = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (0I,1I)
Line 1,170:
printfn "\nBenford's law for 1 through 9:"
benfordLawFigures |> List.iter (fun f -> printf $"{f:N5} ")
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,182:
 
=={{header|Factor}}==
<langsyntaxhighlight lang=factor>USING: assocs compiler.tree.propagation.call-effect formatting
kernel math math.functions math.statistics math.text.utils
sequences ;
Line 1,210:
.header leading histogram [ .digit-report ] assoc-each ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,226:
 
=={{header|Forth}}==
<langsyntaxhighlight lang=forth>: 3drop drop 2drop ;
: f2drop fdrop fdrop ;
 
Line 1,269:
set-precision ;
 
: compute-benford tally report ;</langsyntaxhighlight>
{{Out}}
<pre>Gforth 0.7.2, Copyright (C) 1995-2008 Free Software Foundation, Inc.
Line 1,289:
=={{header|Fortran}}==
FORTRAN 90. Compilation and output of this program using emacs compile command and a fairly obvious Makefile entry:
<langsyntaxhighlight lang=fortran>-*- mode: compilation; default-directory: "/tmp/" -*-
Compilation started at Sat May 18 01:13:00
 
Line 1,297:
0.300999999 0.177000001 0.125000000 9.60000008E-02 7.99999982E-02 6.70000017E-02 5.70000000E-02 5.29999994E-02 4.50000018E-02 LEADING FIBONACCI DIGIT
 
Compilation finished at Sat May 18 01:13:00</langsyntaxhighlight>
 
<langsyntaxhighlight lang=fortran>subroutine fibber(a,b,c,d)
! compute most significant digits, Fibonacci like.
implicit none
Line 1,367:
write(6,*) (benfordsLaw(i),i=1,9),'THE LAW'
write(6,*) (count(i)/1000.0 ,i=1,9),'LEADING FIBONACCI DIGIT'
end program benford</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
{{libheader|GMP}}
<langsyntaxhighlight lang=freebasic>' version 27-10-2016
' compile with: fbc -s console
 
Line 1,460:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>First 1000 Fibonacci numbers
Line 1,498:
 
=={{header|Go}}==
<langsyntaxhighlight lang=go>package main
 
import (
Line 1,528:
math.Log10(1+1/float64(i+1)))
}
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,548:
Uses [[Fibonacci_sequence#Analytic_8|Fibonacci sequence analytic formula]]
{{trans|Java}}
<langsyntaxhighlight lang=groovy>def tallyFirstDigits = { size, generator ->
def population = (0..<size).collect { generator(it) }
def firstDigits = [0]*10
Line 1,555:
}
firstDigits
}</langsyntaxhighlight>
 
'''Test:'''
<langsyntaxhighlight lang=groovy>def digitCounts = tallyFirstDigits(1000, aFib)
println "d actual predicted"
(1..<10).each {
printf ("%d %10.6f %10.6f\n", it, digitCounts[it]/1000, Math.log10(1.0 + 1.0/it))
}</langsyntaxhighlight>
 
'''Output:'''
Line 1,577:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=haskell>import qualified Data.Map as M
import Data.Char (digitToInt)
 
Line 1,598:
| d <- [1 .. 9] ]
 
main = print tab</langsyntaxhighlight>
{{out}}
<pre>[(1,0.301,0.301029995663981),
Line 1,615:
The following solution works in both languages.
 
<langsyntaxhighlight lang=unicon>global counts, total
 
procedure main()
Line 1,648:
if n%2 = 1 then return [c+d, d]
else return [d, c]
end</langsyntaxhighlight>
 
Sample run:
Line 1,668:
=={{header|J}}==
We show the correlation coefficient of Benford's law with the leading digits of the first 1000 Fibonacci numbers is almost unity.
<langsyntaxhighlight lang=J>log10 =: 10&^.
benford =: log10@:(1+%)
assert '0.30 0.18 0.12 0.10 0.08 0.07 0.06 0.05 0.05' -: 5j2 ": benford >: i. 9
Line 1,703:
assert '0.9999' -: 6j4 ": (normalize TALLY_BY_KEY) r benford >: i.9
 
assert '0.9999' -: 6j4 ": TALLY_BY_KEY r benford >: i.9 NB. Of course we don't need normalization</langsyntaxhighlight>
 
=={{header|Java}}==
<langsyntaxhighlight lang=Java>import java.math.BigInteger;
import java.util.Locale;
 
Line 1,734:
}
}
}</langsyntaxhighlight>
The output is:
<pre>1 0.301000 0.301030
Line 1,748:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang=javascript>const fibseries = n => [...Array(n)]
.reduce(
(fib, _, i) => i < 2 ? (
Line 1,766:
]);
 
console.log(benford(fibseries(1000)))</langsyntaxhighlight>
{{output}}
<pre>0: (3) [1, 0.301, 0.3010299956639812]
Line 1,782:
This implementation shows the observed and expected number of occurrences together with the χ² statistic.
 
For the sake of being self-contained, the following includes a generator for Fibonacci numbers, and a prime number generator that is inefficient but brief and can generate numbers within an arbitrary range.<langsyntaxhighlight lang=jq># Generate the first n Fibonacci numbers: 1, 1, ...
# Numerical accuracy is insufficient beyond about 1450.
def fibonacci(n):
Line 1,888:
;
 
task</langsyntaxhighlight>
{{out}}
<pre>First 100 fibonacci numbers:
Line 1,962:
=={{header|Julia}}==
 
<langsyntaxhighlight lang=Julia>fib(n) = ([one(n) one(n) ; one(n) zero(n)]^n)[1,2]
 
ben(l) = [count(x->x==i, map(n->string(n)[1],l)) for i='1':'9']./length(l)
 
benford(l) = [Number[1:9;] ben(l) log10(1.+1./[1:9;])]</langsyntaxhighlight>
{{Out}}
<pre>julia> benford([fib(big(n)) for n = 1:1000])
Line 1,982:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>import java.math.BigInteger
 
interface NumberGenerator {
Line 2,020:
}
 
fun main(a: Array<String>) = println(Benford(FibonacciGenerator))</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
Using function from
http://rosettacode.org/wiki/Fibonacci_sequence#Liberty_BASIC
<syntaxhighlight lang=lb>
<lang lb>
dim bin(9)
 
Line 2,061:
fiboI = a
end function
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,078:
 
=={{header|Lua}}==
<langsyntaxhighlight lang=lua>actual = {}
expected = {}
for i = 1, 9 do
Line 2,097:
for i = 1, 9 do
print(i, actual[i] / n, expected[i])
end</langsyntaxhighlight>
{{out}}
<pre>digit actual expected
Line 2,111:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=mathematica>fibdata = Array[First@IntegerDigits@Fibonacci@# &, 1000];
Table[{d, N@Count[fibdata, d]/Length@fibdata, Log10[1. + 1/d]}, {d, 1,
9}] // Grid</langsyntaxhighlight>
{{out}}
<pre>1 0.301 0.30103
Line 2,126:
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang=NetRexx>/* NetRexx */
options replace format comments java crossref symbols nobinary
 
Line 2,167:
brenfordDeveation(fibList)
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,184:
 
=={{header|Nim}}==
<langsyntaxhighlight lang=Nim>import math
import strformat
 
Line 2,260:
let distrib = actualDistrib(fibSeq)
echo "Fibonacci numbers first digit distribution:\n"
distrib.display()</langsyntaxhighlight>
 
{{out}}
Line 2,279:
=={{header|Oberon-2}}==
{{Works with|oo2c version 2}}
<langsyntaxhighlight lang=oberon2>
MODULE BenfordLaw;
IMPORT
Line 2,323:
END
END BenfordLaw.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,343:
https://rosettacode.org/wiki/Fibonacci_sequence#Arbitrary_Precision<br>
Note the remark about the compilation of the program there.
<langsyntaxhighlight lang=ocaml>
open Num
 
Line 2,374:
List.iter (Printf.printf "%f ") (List.map benfords_law xvalues) ;
Printf.printf "\n" ;;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,384:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang=parigp>distribution(v)={
my(t=vector(9,n,sum(i=1,#v,v[i]==n)));
print("Digit\tActual\tExpected");
Line 2,392:
lucas(n)=fibonacci(n-1)+fibonacci(n+1);
dist(fibonacci)
dist(lucas)</langsyntaxhighlight>
{{out}}
<pre>Digit Actual Expected
Line 2,417:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang=pascal>program fibFirstdigit;
{$IFDEF FPC}{$MODE Delphi}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF}
uses
Line 2,469:
writeln(i:5,dgtCnt[i]:7,expectedCnt[i]:10,reldiff:10:5,' %');
end;
end.</langsyntaxhighlight>
 
<pre>Digit Count Expected rel Diff
Line 2,483:
 
=={{header|Perl}}==
<langsyntaxhighlight lang=Perl>#!/usr/bin/perl
use strict ;
use warnings ;
Line 2,507:
$result = sprintf ( "%.2f" , 100 * $expected[ $i - 1 ] ) ;
printf "%15s %%\n" , $result ;
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,524:
=={{header|Phix}}==
{{trans|Go}}
<!--<langsyntaxhighlight lang=Phix>(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">benford</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">string</span> <span style="color: #000000;">title</span><span style="color: #0000FF;">)</span>
Line 2,554:
<span style="color: #000000;">benford</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">sq_power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">500</span><span style="color: #0000FF;">)),</span><span style="color: #008000;">"First 500 powers of three"</span><span style="color: #0000FF;">)}</span>
<span style="color: #7060A8;">papply</span><span style="color: #0000FF;">(</span><span style="color: #004600;">true</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">printf</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,{</span><span style="color: #008000;">"%-40s%-40s%-40s\n"</span><span style="color: #0000FF;">},</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,571:
 
=={{header|Picat}}==
<langsyntaxhighlight lang=Picat>go =>
 
N = 1000,
Line 2,600:
foreach(E in List)
Map.put(E, cond(Map.has_key(E),Map.get(E)+1,1))
end.</langsyntaxhighlight>
 
{{out}}
Line 2,633:
=={{header|PicoLisp}}==
Picolisp does not support floating point math, but it can call libc math functions and convert the results to a fixed point number for e.g. natural logarithm.
<langsyntaxhighlight lang=PicoLisp>
(scl 4)
(load "@lib/misc.l")
Line 2,671:
 
(bye)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,687:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang=PL/I>
(fofl, size, subrg):
Benford: procedure options(main); /* 20 October 2013 */
Line 2,727:
end tally;
end Benford;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 2,743:
 
=={{header|PL/pgSQL}}==
<langsyntaxhighlight lang=SQL>
WITH recursive
constant(val) AS
Line 2,778:
(select cast(corr(probability_theoretical,probability_real) as numeric(5,4)) correlation
from benford) c
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
The sample file was not found. I selected another that contained the first two-thousand in the Fibonacci sequence, so there is a small amount of extra filtering.
<langsyntaxhighlight lang=PowerShell>
$url = "https://oeis.org/A000045/b000045.txt"
$file = "$env:TEMP\FibonacciNumbers.txt"
Line 2,799:
 
Remove-Item -Path $file -Force -ErrorAction SilentlyContinue
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,818:
{{works with|SWI Prolog|6.2.6 by Jan Wielemaker, University of Amsterdam}}
Note: SWI Prolog implements arbitrary precision integer arithmetic through use of the GNU MP library
<langsyntaxhighlight lang=Prolog>%_________________________________________________________________
% Does the Fibonacci sequence follow Benford's law?
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Line 2,861:
findall(B, (between(1,9,N), benford(N,B)), Benford),
findall(C, firstchar(C), Fc), freq(Fc, Freq),
writeHdr, maplist(writeData, Benford, Freq).</langsyntaxhighlight>
{{out}}
<pre>?- go.
Line 2,876:
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=purebasic>#MAX_N=1000
NewMap d1.i()
Dim fi.s(#MAX_N)
Line 2,915:
 
PrintN(~"\nPress Enter...")
Input()</langsyntaxhighlight>
{{out}}
<pre>Dig. Cnt. Exp. Dif.
Line 2,933:
=={{header|Python}}==
Works with Python 3.X & 2.7
<langsyntaxhighlight lang=python>from __future__ import division
from itertools import islice, count
from collections import Counter
Line 2,971:
 
# just to show that not all kind-of-random sets behave like that
show_dist("random", islice(heads(rand1000()), 10000))</langsyntaxhighlight>
{{out}}
<pre>fibbed Benfords deviation
Line 3,007:
 
=={{header|R}}==
<syntaxhighlight lang=R>
<lang R>
pbenford <- function(d){
return(log10(1+(1/d)))
Line 3,039:
 
print(data)
</syntaxhighlight>
</lang>
{{out}}
digit obs.frequency exp.frequency dev_percentage
Line 3,053:
 
=={{header|Racket}}==
<langsyntaxhighlight lang=Racket>#lang racket
 
(define (log10 n) (/ (log n) (log 10)))
Line 3,088:
;; 7: 5.8% 5.8%
;; 8: 5.1% 5.1%
;; 9: 4.6% 4.6%</langsyntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2016-10-24}}
<syntaxhighlight lang=raku perl6line>sub benford(@a) { bag +« @a».substr(0,1) }
 
sub show(%distribution) {
Line 3,106:
 
multi MAIN($file) { show benford $file.IO.lines }
multi MAIN() { show benford ( 1, 1, 2, *+* ... * )[^1000] }</langsyntaxhighlight>
 
'''Output:''' First 1000 Fibonaccis
Line 3,137:
For the extra credit stuff, it was chosen to generate Fibonacci and factorials rather than find a
web─page with them listed, &nbsp; as each list is very easy to generate.
<langsyntaxhighlight lang=rexx>/*REXX pgm demonstrates Benford's law applied to 2 common functions (30 dec. digs used).*/
numeric digits length( e() ) - length(.) /*width of (e) for LN & LOG precision.*/
parse arg N .; if N=='' | N=="," then N= 1000 /*allow sample size to be specified. */
Line 3,169:
do f=1 for 9; say pad center(f,7) pad center(format(!.f/N,,length(N-2)),w1) #.f
end /*k*/
return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default (1000 numbers) &nbsp; for the input:}}
<pre>
Line 3,224:
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
# Project : Benford's law
 
Line 3,258:
if y = 1 return 1 ok
if y > 1 return fibonacci(y-1) + fibonacci(y-2) ok
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,275:
=={{header|Ruby}}==
{{trans|Python}}
<langsyntaxhighlight lang=ruby>EXPECTED = (1..9).map{|d| Math.log10(1+1.0/d)}
 
def fib(n)
Line 3,311:
 
# just to show that not all kind-of-random sets behave like that
show_dist("random", random(10000))</langsyntaxhighlight>
 
{{out}}
Line 3,350:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=runbasic>
N = 1000
for i = 0 to N - 1
Line 3,381:
next i
end function
</syntaxhighlight>
</lang>
<table border=1><TR bgcolor=wheat><TD>Digit<td>Actual<td>Expected</td><tr><tr align=right><td>1</td><td>30.100</td><td>30.103</td></tr><tr align=right><td>2</td><td>17.700</td><td>17.609</td></tr><tr align=right><td>3</td><td>12.500</td><td>12.494</td></tr><tr align=right><td>4</td><td> 9.500</td><td> 9.691</td></tr><tr align=right><td>5</td><td> 8.000</td><td> 7.918</td></tr><tr align=right><td>6</td><td> 6.700</td><td> 6.695</td></tr><tr align=right><td>7</td><td> 5.600</td><td> 5.799</td></tr><tr align=right><td>8</td><td> 5.300</td><td> 5.115</td></tr><tr align=right><td>9</td><td> 4.500</td><td> 4.576</td></tr></table>
 
Line 3,389:
This solution uses the ''num'' create for arbitrary-precision integers and the ''num_traits'' create for the ''zero'' and ''one'' implementations. It computes the Fibonacci numbers from scratch via the ''fib'' function.
 
<langsyntaxhighlight lang=rust>
extern crate num_traits;
extern crate num;
Line 3,441:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,457:
 
=={{header|Scala}}==
<langsyntaxhighlight lang=scala>// Fibonacci Sequence (begining with 1,1): 1 1 2 3 5 8 13 21 34 55 ...
val fibs : Stream[BigInt] = { def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j); series(1,0).tail.tail }
 
Line 3,485:
case (k, v) => println( "%d: %5.2f%% | %5.2f%% | %5.4f%%".format(k,v._2*100,v._1*100,math.abs(v._2-v._1)*100) )
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,503:
=={{header|Scheme}}==
{{works with|Chez Scheme}}
<langsyntaxhighlight lang=scheme>; Compute the probability of leading digit d (an integer [1,9]) according to Benford's law.
 
(define benford-probability
Line 3,573:
(display-table "Rnd/1T/1M" (lambda () (1+ (random 1000000000000))) 1000000)
(let ((craters (list->vector (list-read-file "moon_craters.lst"))))
(display-table "Craters/D" (make-vecgen craters) (vector-length craters)))</langsyntaxhighlight>
{{out}}
The first one thousand Fibonnaci numbers.
Line 3,615:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang=ruby>var (actuals, expected) = ([], [])
var fibonacci = 1000.of {|i| fib(i).digit(0) }
 
Line 3,630:
"%.2f".sprintf(100 * expected[i - 1]),
)
}</langsyntaxhighlight>
 
{{out}}
Line 3,651:
The query is the same for any number sequence you care to put in the <tt>benford</tt> table.
 
<langsyntaxhighlight lang=SQL>-- Create table
create table benford (num integer);
 
Line 3,693:
 
-- Tidy up
drop table benford;</langsyntaxhighlight>
 
{{out}}
Line 3,713:
=={{header|Stata}}==
 
<langsyntaxhighlight lang=stata>clear
set obs 1000
scalar phi=(1+sqrt(5))/2
Line 3,737:
8 | 53 51.15252245 |
9 | 45 45.75749056 |
+-----------------------------+</langsyntaxhighlight>
 
Assuming the data are random, one can also do a goodness of fit [https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test chi-square test]:
 
<langsyntaxhighlight lang=stata>// chi-square statistic
chisq=sum((f-p):^2:/p)
chisq
Line 3,748:
chi2tail(8,chisq)
.9999942179
end</langsyntaxhighlight>
 
The p-value is very close to 1, showing that the observed distribution is very close to the Benford law.
Line 3,754:
The fit is not as good with the sequence (2+sqrt(2))^n:
 
<langsyntaxhighlight lang=stata>clear
set obs 500
scalar s=2+sqrt(2)
Line 3,785:
chi2tail(8,chisq)
.0387287805
end</langsyntaxhighlight>
 
Now the p-value is less than the usual 5% risk, and one would reject the hypothesis that the data follow the Benford law.
Line 3,791:
=={{header|Swift}}==
 
<langsyntaxhighlight lang=Swift>import Foundation
 
/* Reads from a file and returns the content as a String */
Line 3,893:
let ben = benford(digit: i+1)
print(String(format: "%d\t%.2f\t\t%.2f\t\t%.4f", i+1,ben*100,temp*100,ben-temp))
}</langsyntaxhighlight>
{{out}}
<pre>$ ./Benford
Line 3,911:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang=tcl>proc benfordTest {numbers} {
# Count the leading digits (RE matches first digit in each number,
# even if negative)
Line 3,929:
[expr {log(1+1./$digit)/log(10)*100.0}]]
}
}</langsyntaxhighlight>
Demonstrating with Fibonacci numbers:
<langsyntaxhighlight lang=tcl>proc fibs n {
for {set a 1;set b [set i 0]} {$i < $n} {incr i} {
lappend result [set b [expr {$a + [set a $b]}]]
Line 3,937:
return $result
}
benfordTest [fibs 1000]</langsyntaxhighlight>
{{out}}
<pre>
Line 3,955:
 
=={{header|VBA (Visual Basic for Application)}}==
<syntaxhighlight lang=vb>
<lang vb>
Sub BenfordLaw()
 
Line 3,987:
 
}
</syntaxhighlight>
</lang>
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang=vfp>
#DEFINE CTAB CHR(9)
#DEFINE COMMA ","
Line 4,031:
RETURN LOG10(1 + 1/d)
ENDFUNC
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,051:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=vlang>import math
 
fn fib1000() []f64 {
Line 4,075:
println(" ${i+1} ${f64(n)/f64(c.len):9.3f} ${math.log10(1+1/f64(i+1)):8.3f}")
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,095:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang=ecmascript>import "/fmt" for Fmt
 
var fib1000 = Fn.new {
Line 4,132:
}
 
show.call(fib1000.call(), "First 1000 Fibonacci numbers:")</langsyntaxhighlight>
 
{{out}}
Line 4,151:
=={{header|zkl}}==
{{trans|Go}}
<langsyntaxhighlight lang=zkl>show( // use list (fib(1)...fib(1000)) --> (1..4.34666e+208)
(0).pump(1000,List,fcn(ab){ab.append(ab.sum(0.0)).pop(0)}.fp(L(1,1))),
"First 1000 Fibonacci numbers");
Line 4,165:
(1.0+1.0/i).log10()))
}
}</langsyntaxhighlight>
{{trans|CoffeeScript}}
<langsyntaxhighlight lang=zkl>var BN=Import("zklBigNum");
 
fcn fibgen(a,b) { return(a,self.fcn.fp(b,a+b)) } //-->L(fib,fcn)
Line 4,187:
println("Leading digital distribution of the first 1,000 Fibonacci numbers");
println("Digit\tActual\tExpected");
foreach i in ([1..9]){ println("%d\t%.3f\t%.3f".fmt(i,actual[i], expected[i-1])); }</langsyntaxhighlight>
{{out}}
<pre>
Line 4,205:
=={{header|ZX Spectrum Basic}}==
{{trans|Liberty BASIC}}
<langsyntaxhighlight lang=zxbasic>10 RANDOMIZE
20 DIM b(9)
30 LET n=100
Line 4,228:
1060 NEXT j
1070 RETURN
</syntaxhighlight>
</lang>
The results obtained are adjusted fairly well, except for the number 8. This occurs with Sinclair BASIC, Sam BASIC and SpecBAS fits.
10,327

edits