We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello! I am new to this forum and I just created this account to ask this question: Why is the code below returning negative values in the log of the array?
float AmountOfFibonacciNumbers = 47;
int[] FibonacciNumbers = new int[ceil(AmountOfFibonacciNumbers / 2) * 2];
int j = 1;
int k = 1;
void setup(){
AmountOfFibonacciNumbers = ceil(AmountOfFibonacciNumbers / 2) * 2;
for (int i = 0; i < AmountOfFibonacciNumbers; i = i + 2){
FibonacciNumbers[i] = j;
FibonacciNumbers[i + 1] = k;
j = j + k;
k = k + j;
}
printArray(FibonacciNumbers);
}
Here is what it returns:
[0] 1 [1] 1 [2] 2 [3] 3 [4] 5 [5] 8 [6] 13 [7] 21 [8] 34 [9] 55 [10] 89 [11] 144 [12] 233 [13] 377 [14] 610 [15] 987 [16] 1597 [17] 2584 [18] 4181 [19] 6765 [20] 10946 [21] 17711 [22] 28657 [23] 46368 [24] 75025 [25] 121393 [26] 196418 [27] 317811 [28] 514229 [29] 832040 [30] 1346269 [31] 2178309 [32] 3524578 [33] 5702887 [34] 9227465 [35] 14930352 [36] 24157817 [37] 39088169 [38] 63245986 [39] 102334155 [40] 165580141 [41] 267914296 [42] 433494437 [43] 701408733 [44] 1134903170 [45] 1836311903 [46] -1323752223 [47] 512559680
If you extend the array further, even more negative numbers pop up. What is going on here?
Any help would be appreciated, thanks! -Gav
Answers
i think you leave the allowed range for int
try double or so in line 2
Hello, I changed the code a little bit and I'm coming across a similar problem that appears around the same part of the array:
Here is what it returns:
It has to do with the way the computer handles numbers. When the number is gets too high it rolls over to its lowest value.
In this code it shows what happens when the number rolls over.
int x = 2147483647; println(x); println(x + 1);
https://Processing.org/reference/long.html
http://Docs.Oracle.com/javase/8/docs/api/java/math/BigInteger.html
Thanks for answering my question! I tried the code you provided and it logged the following:
This bug seems like it could cause problems with all sorts of applications. Do you know what causes this to happen? It's sad that such a powerful API can be hampered by a simple problem like this. If Processing is just a beginner API that isn't designed to handle heavy loads, then I assume I should be learning about a more serious API that is capable of handling numbers larger than 2147483647. What should I do about this?
Thanks!
-Gav
It has nothing to do with how processing handles numbers, but it has everything to do with how computers handle numbers. A different datatype (such as long) may give you better results.
Ah, I see. Each integer exists as part of its own array with a max of 2147483647, and minimum of -2147483648. If I define the numbers as 'long' and convert them to 'int', then I can extend outside of that range.
Edit: Converting back into integers defeats the purpose of using long numbers.