0

I am using procedural generation with the fibonacci sequence and I need to input numbers ranging into the thousands, except when I do so, I keep getting the error Infinite or Nan on this line : "BigDecimal placeholder = new BigDecimal((Math.pow( 1+Math.sqrt(5), n ) - Math.pow( 1-Math.sqrt(5), n)));"

public static BigDecimal fibonacci(double n){
    n = Math.floor(n);

    BigDecimal placeholder = new BigDecimal((Math.pow( 1+Math.sqrt(5), n ) - Math.pow(  1-Math.sqrt(5), n)));
    placeholder.divide(new BigDecimal((Math.pow(2, n)*Math.sqrt(5))), RoundingMode.HALF_UP);
    return placeholder;
}

I would love some help or redirection to another thread and or a better way of going about this.

yole
  • 92,896
  • 20
  • 260
  • 197
Ryan Reed
  • 9
  • 1
  • 3
  • Take a look at this: http://stackoverflow.com/questions/18028454/numberformatexception-infinite-or-nan – antonio Mar 07 '15 at 17:14
  • 2
    Just so you know: you're throwing the result of your `divide` operation away. `placeholder` isn't mutated. – Makoto Mar 07 '15 at 17:15
  • There is not much point using BigDecimal with an operation based on `double` precision. You may as well use `double` all the way, or don't use `double` for operations like `Math.pow` or `Math.sqrt` – Peter Lawrey Mar 07 '15 at 20:22
  • First of all, Math.pow( 1+Math.sqrt(5), 1000 ) cannot be represented as a double : the value is too high. This expression results in Double.Inf. And no BigDecimal can represent infinity. You have to build a BigDecimal before it is to big. Fortunaly the power argument is an integer and the function `.pow(Integer i)` is available on BigDecimal (as well as `sqrt()` since java 9). Then you handle the computation with BigDecimal all the way. – Pierre Demeestere Nov 15 '22 at 21:59

0 Answers0