Search code examples
javamathbigdecimal

java.lang.NumberFormatException with BigDecimal java


I implemented this short code to calculate the (n)th Fibonacci number, but when it gets too big, my BigDecimal doesn't seem to work anymore. I get the following stacktrace:

Exception in thread "main" java.lang.NumberFormatException
  at java.math.BigDecimal.<init>(BigDecimal.java:494)
    at java.math.BigDecimal.<init>(BigDecimal.java:383)
    at java.math.BigDecimal.<init>(BigDecimal.java:806)
    at java.math.BigDecimal.valueOf(BigDecimal.java:1274)
    at Fibonacci.next2(Fibonacci.java:42)
    at FibonacciPrint.main(FibonacciPrint.java:23)

Here is my code:

int index;

public Fibonacci(int index){
    this.index=index;
}

public  BigDecimal next2(){
    System.out.print(index + " ");

    return BigDecimal.valueOf(((Math.pow(1 + Math.sqrt(5), index)- 
                                Math.pow(1-Math.sqrt(5),index))
                                /(Math.pow(2,index)* Math.sqrt(5))));

}

and the print class:

Fibonacci f2 = new Fibonacci(Integer.parseInt(args[0]));

long startTime2 = System.currentTimeMillis();

line 23:

    System.out.println(f2.next2());
    long endTime2 = System.currentTimeMillis();
    System.out.println("Total execution time: " + (endTime2-startTime2) + "ms");

Does anyone have an idea how to fix this?


Solution

  • BigDecimal is unbounded, but the double value you initiate it:

    ((Math.pow(1 + Math.sqrt(5), index) -
                    Math.pow(1 - Math.sqrt(5), index))
                    / (Math.pow(2, index) * Math.sqrt(5)));
    

    might be NaN, which cause this exception.

    You can use BigDecimal.pow instead Math.pow.