Benford's law: Difference between revisions

From Rosetta Code
Content added Content deleted
(Promote from draft)
m (→‎{{header|REXX}}: added primes and factorials to the output. -- ~~~~)
Line 267: Line 267:
The REXX language practically hasn't any high math functions, so the '''E''', '''LN''', and '''LOG''' functions were included herein.
The REXX language practically hasn't any high math functions, so the '''E''', '''LN''', and '''LOG''' functions were included herein.
<br>Note that the '''E''' and '''LN10''' functions return a limited amount of accuracy, and they should be greater then 50 digits (in this case).
<br>Note that the '''E''' and '''LN10''' functions return a limited amount of accuracy, and they should be greater then 50 digits (in this case).
<br><br>Note that prime numbers don't lend themselves to Benford's law.
<lang rexx>/*REXX program demonstrates some common trig functions (30 digits shown)*/
<lang rexx>/*REXX program demonstrates some common trig functions (30 digits shown)*/
numeric digits 2000 /*be able to accuratly calc FIBs.*/
numeric digits 50 /*use only 50 digits for LN, LOG.*/
parse arg N .; if N=='' then N=1000 /*allow sample size specification*/
parse arg N .; if N=='' then N=1000 /*allow sample size specification*/
/*══════════════apply Benford's law to Fibonacci numbers.*/
/*══════════════apply Benford's law to Fibonacci numbers.*/
@.=1; do j=3 to N; jm1=j-1; jm2=j-2; @.j=@.jm2+@.jm1; end /*j*/
@.=1; do j=3 to N; jm1=j-1; jm2=j-2; @.j=@.jm2+@.jm1; end /*j*/
call show_results "Benford's law applied to Fibonacci numbers"
call show_results "Benford's law applied to" N 'Fibonacci numbers'
/*══════════════apply Benford's law to prime numbers. */
p=0; do j=2 until p==N; if \isPrime(j) then iterate; p=p+1; @.p=j;end
call show_results "Benford's law applied to" N 'prime numbers'
/*══════════════apply Benford's law to factorials. */
do j=1 for N; @.j=!(j); end /*j*/
call show_results "Benford's law applied to" N 'factorial products'
exit /*stick a fork in it, we're done.*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────SHOW_RESULRS subroutine─────────────*/
/*──────────────────────────────────SHOW_RESULTS subroutine─────────────*/
show_results: w1=max(length('obsserved'),length(N-2))
show_results: w1=max(length('obsserved'),length(N-2)) ; say
pad=' '; w2=max(length('expected' ),length(N ))
pad=' '; w2=max(length('expected' ),length(N ))
say pad 'digit' pad center('observed',w1) pad center('expected',w2)
say pad 'digit' pad center('observed',w1) pad center('expected',w2)
say pad '─────' pad center('',w1,'─') pad center('',w2,'─') pad arg(1)
say pad '─────' pad center('',w1,'─') pad center('',w2,'─') pad arg(1)
!.=0; do j=1 for N; _=left(@.j,1); !._=!._+1; end /*get 1st digits.*/
!.=0; do j=1 for N; _=left(@.j,1); !._=!._+1; end /*get 1st digits.*/
numeric digits 50 /*use only 50 digits for LN, LOG.*/


do k=1 for 9 /*show results for Fibonacci nums*/
do k=1 for 9 /*show results for Fibonacci nums*/
Line 288: Line 294:
return
return
/*──────────────────────────────────one─line subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
/*──────────────────────────────────one─line subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/
!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end /*j*/; return !
e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535
e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535
isprime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1; if x//2==0 then return 0; if x//3==0 then return 0; do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end; return 1
log:return ln(arg(1))/ln(10)
ln10:return 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959829834196778404228624863340952546508280675666628736909878168948290720832555468084379989482623319852839350530896538
ln10:return 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959829834196778404228624863340952546508280675666628736909878168948290720832555468084379989482623319852839350530896538
ln:procedure expose $.;parse arg x,f;if x==10 then do;_=ln10();xx=format(_);if xx\==_ then return xx;end;call e;ig=x>1.5;is=1-2*(ig\==1);ii=0;xx=x;return .ln_comp()
ln:procedure expose $.;parse arg x,f;if x==10 then do;_=ln10();xx=format(_);if xx\==_ then return xx;end;call e;ig=x>1.5;is=1-2*(ig\==1);ii=0;xx=x;return .ln_comp()
.ln_comp:do while ig&xx>1.5|\ig&xx<.5;_=e();do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end;xx=izz;ii=ii+is*2**k;end;x=x*e()**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii</lang>
.ln_comp:do while ig&xx>1.5|\ig&xx<.5;_=e();do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end;xx=izz;ii=ii+is*2**k;end;x=x*e()**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii
log:return ln(arg(1))/ln(10)</lang>
'''output''' when using the default input:
'''output''' when using the default input:
<pre style="overflow:scroll">
<pre style="overflow:scroll">
digit observed expected
digit observed expected
───── ───────── ──────── Benford's law applied to Fibonacci numbers
───── ───────── ──────── Benford's law applied to 1000 Fibonacci numbers
1 0.301 0.301030
1 0.301 0.301030
2 0.177 0.176091
2 0.177 0.176091
Line 306: Line 314:
8 0.053 0.051153
8 0.053 0.051153
9 0.045 0.045757
9 0.045 0.045757

digit observed expected
───── ───────── ──────── Benford's law applied to 1000 prime numbers
1 0.160 0.301030
2 0.146 0.176091
3 0.139 0.124939
4 0.139 0.096910
5 0.131 0.079181
6 0.135 0.066947
7 0.118 0.057992
8 0.017 0.051153
9 0.015 0.045757

digit observed expected
───── ───────── ──────── Benford's law applied to 1000 factorial products
1 0.293 0.301030
2 0.176 0.176091
3 0.124 0.124939
4 0.102 0.096910
5 0.069 0.079181
6 0.087 0.066947
7 0.051 0.057992
8 0.051 0.051153
9 0.047 0.045757
</pre>
</pre>



Revision as of 23:34, 13 May 2013

Task
Benford's law
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Benford's_law. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)

Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution.

This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude.

A set of numbers is said to satisfy Benford's law if the leading digit d (d ∈ {1, ..., 9}) occurs with probability

 

For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever).

Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution.

For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.

See also:

Haskell

<lang haskell>import qualified Data.Map as M

fstdigit :: Integer -> Int fstdigit = head . map (read . (:[])) . show

n = 1000::Int fibs = 1:1:zipWith (+) fibs (tail fibs) fibdata = map fstdigit $ take n fibs freqs = M.fromListWith (+) $ zip fibdata (repeat 1)

tab :: [(Int, Double, Double)] tab = [(d,

      (fromIntegral (M.findWithDefault 0 d freqs) /(fromIntegral n) ),
       logBase 10.0 $ 1 + 1/(fromIntegral d) ) | d<-[1..9]]

main = print tab </lang>

Output:
[(1,0.301,0.301029995663981),
(2,0.177,0.176091259055681),
(3,0.125,0.1249387366083),
(4,0.096,0.0969100130080564),
(5,0.08,0.0791812460476248),
(6,0.067,0.0669467896306132),
(7,0.056,0.0579919469776867),
(8,0.053,0.0511525224473813),
(9,0.045,0.0457574905606751)]

Mathematica

<lang mathematica>fibdata = Array[First@IntegerDigits@Fibonacci@# &, 1000]; Table[{d, N@Count[fibdata, d]/Length@fibdata, Log10[1. + 1/d]}, {d, 1,

   9}] // Grid</lang>
Output:
1	0.301	0.30103
2	0.177	0.176091
3	0.125	0.124939
4	0.096	0.09691
5	0.08	0.0791812
6	0.067	0.0669468
7	0.056	0.0579919
8	0.053	0.0511525
9	0.045	0.0457575

Perl

<lang Perl>#!/usr/bin/perl use strict ; use warnings ; use POSIX qw( log10 ) ;

my @fibonacci = ( 0 , 1 ) ; while ( @fibonacci != 1000 ) {

  push @fibonacci , $fibonacci[ -1 ] + $fibonacci[ -2 ] ;

} my @actuals ; my @expected ; for my $i( 1..9 ) {

  my $sum = 0 ;
  map { $sum++ if $_ =~ /\A$i/ } @fibonacci ;
  push @actuals , $sum / 1000  ;
  push @expected , log10( 1 + 1/$i ) ;

} print " Observed Expected\n" ; for my $i( 1..9 ) {

  print "$i : " ;
  my $result = sprintf ( "%.2f" , 100 * $actuals[ $i - 1 ] ) ;
  printf "%11s %%" , $result ;
  $result = sprintf ( "%.2f" , 100 * $expected[ $i - 1 ] ) ;
  printf "%15s %%\n" , $result ;

}</lang>

Output:
 
         Observed         Expected
1 :       30.10 %          30.10 %
2 :       17.70 %          17.61 %
3 :       12.50 %          12.49 %
4 :        9.50 %           9.69 %
5 :        8.00 %           7.92 %
6 :        6.70 %           6.69 %
7 :        5.60 %           5.80 %
8 :        5.30 %           5.12 %
9 :        4.50 %           4.58 %

Perl 6

<lang perl6>sub benford (@a) { @a.grep(/<[1..9]>/)».match(/<[1..9]>/).bag }

sub dump (%distribution, $base = 10) {

   printf "%9s %9s  %s\n", <Actual Expected Deviation>;
   for 1 .. 9 -> $digit {
       my $actual = %distribution{$digit} * 100 / [+] %distribution.values;
       my $expected = (1 + 1 / $digit).log($base) * 100;
       printf "%d: %5.2f%% | %5.2f%% | %.2f%%\n",
         $digit, $actual, $expected, abs($expected - $actual);
   }

}

( 1, 1, 2, *+* ... * )[^1000].&benford.&dump;</lang>

Output: First 1000 Fibonaccis

   Actual  Expected  Deviation
1: 30.10% | 30.10% | 0.00%
2: 17.70% | 17.61% | 0.09%
3: 12.50% | 12.49% | 0.01%
4:  9.60% |  9.69% | 0.09%
5:  8.00% |  7.92% | 0.08%
6:  6.70% |  6.69% | 0.01%
7:  5.60% |  5.80% | 0.20%
8:  5.30% |  5.12% | 0.18%
9:  4.50% |  4.58% | 0.08%

Extra credit: Square Kilometers of land under cultivation, by country / territory. First column from Wikipedia: Land use statistics by country.

   Actual  Expected  Deviation
1: 33.33% | 30.10% | 3.23%
2: 18.31% | 17.61% | 0.70%
3: 13.15% | 12.49% | 0.65%
4:  8.45% |  9.69% | 1.24%
5:  9.39% |  7.92% | 1.47%
6:  5.63% |  6.69% | 1.06%
7:  4.69% |  5.80% | 1.10%
8:  5.16% |  5.12% | 0.05%
9:  1.88% |  4.58% | 2.70%

Python

Works with Python 3.X & 2.7 <lang python>from __future__ import division from itertools import islice from math import log10 from random import randint

expected = [log10(1+1/d) for d in range(1,10)]

def fib():

   a,b = 1,1
   while True:
       yield a
       a,b = b,a+b
  1. powers of 3 as a test sequence

def power_of_threes():

   s = 1
   while True:
       yield s
       s *= 3

def heads(s):

   for a in s: yield int(str(a)[0])

def show_dist(title, s):

   f,size = [0] * 9, 0
   for x in s:
       f[x-1] += 1
       size += 1
   res = [c/size for c in f]
   print("\n%s Benfords deviation" % title)
   for r, e in zip(res, expected):
       print("%5.1f%% %5.1f%%  %5.1f%%" % (r*100., e*100., abs(r - e)*100.))

def rand1000():

   while True: yield randint(1,9999)

if __name__ == '__main__':

   show_dist("fibbed", islice(heads(fib()), 1000))
   show_dist("threes", islice(heads(power_of_threes()), 1000))
   # just to show that not all kind-of-random sets behave like that
   show_dist("random", islice(heads(rand1000()), 10000))</lang>
Output:
fibbed Benfords deviation
 30.1%  30.1%    0.0%
 17.7%  17.6%    0.1%
 12.5%  12.5%    0.0%
  9.6%   9.7%    0.1%
  8.0%   7.9%    0.1%
  6.7%   6.7%    0.0%
  5.6%   5.8%    0.2%
  5.3%   5.1%    0.2%
  4.5%   4.6%    0.1%

threes Benfords deviation
 30.0%  30.1%    0.1%
 17.7%  17.6%    0.1%
 12.3%  12.5%    0.2%
  9.8%   9.7%    0.1%
  7.9%   7.9%    0.0%
  6.6%   6.7%    0.1%
  5.9%   5.8%    0.1%
  5.2%   5.1%    0.1%
  4.6%   4.6%    0.0%

random Benfords deviation
 11.2%  30.1%   18.9%
 10.9%  17.6%    6.7%
 11.6%  12.5%    0.9%
 11.1%   9.7%    1.4%
 11.6%   7.9%    3.7%
 11.4%   6.7%    4.7%
 10.3%   5.8%    4.5%
 11.0%   5.1%    5.9%
 10.9%   4.6%    6.3%

Racket

<lang Racket>

  1. lang racket

(define (log10 n) (/ (log n) (log 10)))

(define (first-digit n)

 (quotient n (expt 10 (inexact->exact (floor (log10 n))))))

(define N 10000)

(define fibs

 (let loop ([n N] [a 0] [b 1])
   (if (zero? n) '() (cons b (loop (sub1 n) b (+ a b))))))

(define v (make-vector 10 0)) (for ([n fibs])

 (define f (first-digit n))
 (vector-set! v f (add1 (vector-ref v f))))

(printf "N OBS EXP\n") (define (pct n) (~r (* n 100.0) #:precision 1 #:min-width 4)) (for ([i (in-range 1 10)])

 (printf "~a: ~a% ~a%\n" i
         (pct (/ (vector-ref v i) N))
         (pct (log10 (+ 1 (/ i))))))
Output
N OBS EXP
1
30.1% 30.1%
2
17.6% 17.6%
3
12.5% 12.5%
4
9.7% 9.7%
5
7.9% 7.9%
6
6.7% 6.7%
7
5.8% 5.8%
8
5.1% 5.1%
9
4.6% 4.6%

</lang>

REXX

The REXX language practically hasn't any high math functions, so the E, LN, and LOG functions were included herein.
Note that the E and LN10 functions return a limited amount of accuracy, and they should be greater then 50 digits (in this case).

Note that prime numbers don't lend themselves to Benford's law. <lang rexx>/*REXX program demonstrates some common trig functions (30 digits shown)*/ numeric digits 50 /*use only 50 digits for LN, LOG.*/ parse arg N .; if N== then N=1000 /*allow sample size specification*/

              /*══════════════apply Benford's law to Fibonacci numbers.*/

@.=1; do j=3 to N; jm1=j-1; jm2=j-2; @.j=@.jm2+@.jm1; end /*j*/ call show_results "Benford's law applied to" N 'Fibonacci numbers'

              /*══════════════apply Benford's law to prime numbers.    */

p=0; do j=2 until p==N; if \isPrime(j) then iterate; p=p+1; @.p=j;end call show_results "Benford's law applied to" N 'prime numbers'

              /*══════════════apply Benford's law to factorials.       */
        do j=1  for N;      @.j=!(j);  end  /*j*/

call show_results "Benford's law applied to" N 'factorial products' exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SHOW_RESULTS subroutine─────────────*/ show_results: w1=max(length('obsserved'),length(N-2))  ; say pad=' '; w2=max(length('expected' ),length(N )) say pad 'digit' pad center('observed',w1) pad center('expected',w2) say pad '─────' pad center(,w1,'─') pad center(,w2,'─') pad arg(1) !.=0; do j=1 for N; _=left(@.j,1); !._=!._+1; end /*get 1st digits.*/

       do k=1  for 9                  /*show results for Fibonacci nums*/
       say pad center(k,5) pad center(format(!.k/N,,length(N-2)),w1),
                           pad center(format(log(1+1/k),,length(N)+2),w2)
       end   /*k*/

return /*──────────────────────────────────one─line subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ !: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end /*j*/; return ! e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 isprime: procedure; parse arg x; if wordpos(x,'2 3 5 7')\==0 then return 1; if x//2==0 then return 0; if x//3==0 then return 0; do j=5 by 6 until j*j>x; if x//j==0 then return 0; if x//(j+2)==0 then return 0; end; return 1 ln10:return 2.30258509299404568401799145468436420760110148862877297603332790096757260967735248023599720508959829834196778404228624863340952546508280675666628736909878168948290720832555468084379989482623319852839350530896538 ln:procedure expose $.;parse arg x,f;if x==10 then do;_=ln10();xx=format(_);if xx\==_ then return xx;end;call e;ig=x>1.5;is=1-2*(ig\==1);ii=0;xx=x;return .ln_comp() .ln_comp:do while ig&xx>1.5|\ig&xx<.5;_=e();do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end;xx=izz;ii=ii+is*2**k;end;x=x*e()**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii log:return ln(arg(1))/ln(10)</lang> output when using the default input:

    digit     observed      expected
    ─────     ─────────     ────────     Benford's law applied to 1000 Fibonacci numbers
      1         0.301       0.301030
      2         0.177       0.176091
      3         0.125       0.124939
      4         0.096       0.096910
      5         0.080       0.079181
      6         0.067       0.066947
      7         0.056       0.057992
      8         0.053       0.051153
      9         0.045       0.045757

    digit     observed      expected
    ─────     ─────────     ────────     Benford's law applied to 1000 prime numbers
      1         0.160       0.301030
      2         0.146       0.176091
      3         0.139       0.124939
      4         0.139       0.096910
      5         0.131       0.079181
      6         0.135       0.066947
      7         0.118       0.057992
      8         0.017       0.051153
      9         0.015       0.045757

    digit     observed      expected
    ─────     ─────────     ────────     Benford's law applied to 1000 factorial products
      1         0.293       0.301030
      2         0.176       0.176091
      3         0.124       0.124939
      4         0.102       0.096910
      5         0.069       0.079181
      6         0.087       0.066947
      7         0.051       0.057992
      8         0.051       0.051153
      9         0.047       0.045757

Scala

<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 }


/**

* Given a numeric sequence, return the distribution of the most-signicant-digit 
* as expected by Benford's Law and then by actual distribution.
*/

def benford[N:Numeric]( data:Seq[N] ) : Map[Int,(Double,Double)] = {

 import scala.math._
 
 val maxSize = 10000000  // An arbitrary size to avoid problems with endless streams
 
 val size = (data.take(maxSize)).size.toDouble
 
 val distribution = data.take(maxSize).groupBy(_.toString.head.toString.toInt).map{ case (d,l) => (d -> l.size) }
 
 (for( i <- (1 to 9) ) yield { (i -> (log10(1D + 1D / i), (distribution(i) / size))) }).toMap

}

{

 println( "Fibonacci Sequence (size=1000): 1 1 2 3 5 8 13 21 34 55 ...\n" )
 println( "%9s %9s %9s".format( "Actual", "Expected", "Deviation" ) )
 benford( fibs.take(1000) ).toList.sorted foreach { 
   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) ) 
 }

}</lang>

Output:
Fibonacci Sequence (size=1000): 1 1 2 3 5 8 13 21 34 55 ...

   Actual  Expected Deviation
1: 30.10% | 30.10% | 0.0030%
2: 17.70% | 17.61% | 0.0909%
3: 12.50% | 12.49% | 0.0061%
4:  9.60% |  9.69% | 0.0910%
5:  8.00% |  7.92% | 0.0819%
6:  6.70% |  6.69% | 0.0053%
7:  5.60% |  5.80% | 0.1992%
8:  5.30% |  5.12% | 0.1847%
9:  4.50% |  4.58% | 0.0757%