Home > Enterprise >  Java double to int convertion changes sign of result
Java double to int convertion changes sign of result

Time:08-12

I tried to calculate a series of the N first fibonacci numbers using Binets Formula.

Every result i get is correct until F47 where the result is NEGATIVE.

This is my result : -1323752223
And heres the expected result : 2971215073

I really think the problem occures during the double to int conversion

Source Code:

 import java.lang.Math;

class fibonacci{
  public static int NthFibonacci(int n){
    double fi = 1.61803398875;
    int fb = (int)Math.round((Math.pow(fi,n) - Math.pow(1-fi,n))/Math.sqrt(5));
    return fb;
  }

  public static void FibonacciSeries(Integer n){
    for(int i = 0; i < n; i  ){
      System.out.println(NthFibonacci(i)   " ");
    }
  }  
  public static void main(String[] args) {
    FibonacciSeries(50);
  }
}

CodePudding user response:

I think that the problem does not have something to do with the double conversion.

int can store numbers that can be represented by 32 bits. This means the highest number integer can represents is 2.147.483.647.

The F47 is breaking this limit and results in an bit-overflow, so it starts at -2.147.483.68 and adds the rest of your 2971215073 - 2147483647 to it. -1323752223 is the outcome.

Use a long (64bit) instead of an int and you should be good :)

CodePudding user response:

2971215073 is too big to be represented as an int at all. The maximum value of an int -- Integer.MAX_VALUE -- is 2^31 - 1, or 2147483647.

  •  Tags:  
  • java
  • Related