Unexpected negative numbers in Java
import java.util.*;
public class Prac9FibonacciNumbers {
public static void main(String[] args) {
int[] x = new int[100];
x[0] = 1;
x[1] = 1;
for (int a = 2; a < 100; a++) {
x[a] = x[a - 1] + x[a - 2];
}
for (int a = 0; a < 100; a++) {
if(a < 99){
System.out.print(x[a] + ",");
}
else{
System.out.print(x[a]);
}
}
}
}
This program is designed to create a list of Fibonacci numbers. However, for some reason, it gives me negative numbers right in the middle of my output.
I could use
Math.abs()
but I want to know why it is giving me negative numbers. The output is below. Please help me understand this problem.
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368,75025,121393,196418,317811,514229, 832040, 1346269,2178309,3524578,5702887,9227465,14930352,24157817,39088169,63245986,102334155,165580141,267914296,433494437,701408733,1134903170,1836311903, -1323752223,511862925640, -1323752223,511862582680 , 368225352,2144908973, -1781832971,363076002, -1418756969, -1055680967,1820529360,764848393, -1709589543, -944741150,1640636603,695895453, -1958435240, -1273425691,87,8 -433386095, 1845853122,1412467027, -1036647147,375819880, -660827267, -285007387, -945834654, -1230842041,2118290601,887448560, -1289228135, -401779575, -2011910087710, 16910087710, 572466946, -2079590721, -1507123775,708252800, -798870975, -90618175, -889489150, -980107325
source to share
Fibonacci numbers will rise quite quickly. On the 46th number, you start getting negative numbers, for example. -1323752223
... This is because the numbers have gotten so large that they overflow the datatype int
.
You can use arrays long[]
, but that will only postpone the problem. You will start getting negative numbers on the 92nd number, for example. -6246583658587674878
because it will overflow the datatype long
.
The use double
will not have the required accuracy at this value. You can use BigInteger
s, which have arbitrary precision and magnitude.
BigInteger[] x = new BigInteger[100];
x[0] = BigInteger.ONE;
x[1] = BigInteger.ONE;
And you will need to use the method add
.
x[a] = x[a - 1].add(x[a - 2]);
source to share
In the Java Language Specification for Integer Operations:
The built-in integer operators do not indicate overflow or underflow in any way. The results are language-specific and do not depend on the JVM version: Integer.MAX_VALUE + 1 == Integer.MIN_VALUE and Integer.MIN_VALUE - 1 == Integer.MAX_VALUE. The same goes for other integer types.
If you do something like this:
int x = 2147483647;
x++;
If you are now printing x it will be the value -2147483648
Use the biginteger datatype to declare your array.
source to share