Rmyers
Rmyers

Reputation: 217

Benfords Law in Java

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

Upvotes: 1

Views: 756

Answers (1)

tskuzzy
tskuzzy

Reputation: 36476

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

Upvotes: 2

Related Questions