1

I am trying to create a application that will figure out how to find benfords law on a number in the nth position, and so far I haven't been able to do it. I can find it for the number in the first position but I'm not sure after that. Here is a resource on benfords law:

http://www.mathpages.com/home/kmath302/kmath302.htm

There is a mathmatical formula for what I am trying to do at the very bottom (the last formula) but I can't seem to get it into code.

This is how I did it for the first digit at any given position:

public static double probability(int position, int digit)
{   
    double result = Math.log(1+(1/(double) digit))/Math.log(10);
    return result;
}

Any ideas how to implement the summation part of it? I am pretty sure it will involve a for loop but it doesn't seem to work out when I try it.

EDIT----------------------------------------------------------------------------------------

Thanks to tskuzzy's answer I figured it out. This is how you would do it in Java:

public static double probability(int position, int digit) {   
double p = 0.0;

for( int k = (int) Math.pow(10,position-1); k < Math.pow(10,position); k++)
{
    p += Math.log( 1+1.0/(k*10 + digit) );
}

return p/Math.log(10);
}
Rmyers
  • 217
  • 4
  • 14

1 Answers1

2

Yeah, it's just a for-loop:

public static double probability(int position, int digit) {   
    double p = 0.0;

    for( int k = Math.pow(10,position-1); k < Math.pow(10,position); k++ {
        p += Math.log( 1+1.0/(k*10 + digit) );
    }

    return p/Math.log(10);
}
tskuzzy
  • 35,812
  • 14
  • 73
  • 140
  • Thats a great idea, but you can't use a double in a for loop and if you cast k as an int it doesn't work mathematically and thus doesn't return the right answer... – Rmyers Oct 20 '11 at 19:47
  • Wait i tried it the wrong way...this is actually the right answer. Thanks! – Rmyers Oct 20 '11 at 19:49