Last active
September 30, 2015 13:51
-
-
Save goulu/ecbea29f3b7959206ab8 to your computer and use it in GitHub Desktop.
Benford Law Statistics for Google Docs https://docs.google.com/spreadsheet/ccc?key=0Al_D4zS2T4QodHhjM0JxejRKZWpWTWVKUUxISVlfTnc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Google Spreadsheet custom functions for Benford Law statistics | |
author : Philippe Guglielmetti aka Dr. Goulu | |
contact: drgoulu@gmailcom | |
license: LGPL | |
*/ | |
function sum(a, b) { return a + b; } // not predefined ? | |
function log10 (arg) { return Math.log(arg) / 2.302585092994046;} // Math.LN10 | |
function Benford(range, digit,n) { | |
// returns the fraction of cells in range that have their n-th digit equal to digit | |
// see http://en.wikipedia.org/wiki/Benford's_law | |
digit=String(digit); | |
n = typeof n !== 'undefined' ? n-1 : 0; | |
var process = function(cell) { return String(cell)[n]==digit ? 1:0;} | |
var values = range.map(process); | |
return values.reduce(sum, 0)/range.length; | |
} | |
function BenfordLaw(i,n){ | |
//return probability of n-th digit to be a i according to Benford law | |
n = typeof n !== 'undefined' ? n : 1; | |
var s = 0; | |
if (n>1 | i>0) { | |
for (k=Math.floor(Math.pow(10,n-2)); k<Math.pow(10,n-1); k++) { | |
s+=log10(1+1/(10*k+i)) | |
} | |
} | |
return s; | |
} | |
function Chi2(data,model){ | |
result=0; | |
for (i in data) { | |
result=result+Math.pow(data[i]-model[i],2)/model[i]; | |
} | |
return result; | |
} | |
function Chi2Benford(data,n) { | |
n = typeof n !== 'undefined' ? n : 1; | |
var s=data.reduce(sum, 0); | |
var b=new Array(); | |
var d=new Array(); | |
for (i=1; i<10; i++) { | |
b[i]=BenfordLaw(i,n); | |
d[i]=Benford(data,i,n); | |
} | |
return Chi2(d,b); | |
} | |
function main() { | |
Chi2Benford([3,2,1],1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment