Search code examples
javabigdecimalbenfords-law

Benford's Law Program in Java


I am making a program in Java to see if the Benford's Law is actually true. I am using BigDecimal, but there was an error ever since I implemented it.

import java.lang.*;
import java.math.BigDecimal;

public class BenfordLaw {
    public static int oneornot(BigDecimal number) {
        String str2num = number.toString();
        if(str2num.startsWith("1")) {
            return 1;
        } else {
            return 0;
        }
    }
    public static void main(String[] args) {
        int n = 0;
        long sum = 0;
        for (int i = 0; i < 10000; i++) {
            BigDecimal number = BigDecimal.valueOf(Math.pow(2,n));
            System.out.println(number);
            double newnum = oneornot(number);
            sum += newnum;
            n+=1;
        }
        System.out.println(sum);
        System.out.println(sum*0.0001);
     }
}

If you run this program, there is an error. The error is in the link below. https://pastebin.com/ShJmGjdJ


Solution

  • Your program throws exception because of the following line:

    BigDecimal number = BigDecimal.valueOf(Math.pow(2,n));
    

    The variable n is incremented by 1 at every iteration up to 9999. Because of that Math.pow(2,n) is becoming so big, that at some point it exceeds the max value of double type. Eventually Double.toString (which is used by BigDecimal.valueOf) returns "Infinity" what leads to NumberFormatException.

    Please replace the mentioned line with following to fix your problem:

    BigDecimal number = BigDecimal.valueOf(2).pow(n));