Fibonacci even numbers. Code doesn't work for large numbers

2 visualizzazioni (ultimi 30 giorni)
I have writen a code to calculate for every d numbers all the fibonacci numbers that are even, but it doesn't seem to work for large d such as 100 or 150. Can you tell me what i did wrong? My code is this
function y = evenFibo(d)
%y = x;
fibonacci(1) = 0; fibonacci(2) = 1;
for i = 3 : d +1
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2) ;
end
fibonacci = nonzeros(fibonacci);
even = [];
for i = 1 : d
if rem (fibonacci(i),2) == 0 == 1 %einai artios
even = [even, fibonacci(i)];
fibonacci(i)
end
end
y= numel(even);
end

Risposta accettata

John D'Errico
John D'Errico il 11 Lug 2020
Modificato: John D'Errico il 11 Lug 2020
Why are you surprised?
log2(fibonacci(100))
ans =
68.263
You cannot represent an integer exactly in double precision if it is greater than 2^53-1. That appears to happen around n == 79.
log2(fibonacci(79))
ans =
53.684
So while there is nothing overtly wrong with your code, what is wrong is your assumption that you can use double preciion arithmetic to compute the result for large index.
If you seriously need to compute that result for larger indices, then you need to use a tool like the symbolic toolbox, or perhaps my own VPI toolbox, which can handle numbers with more than roughly 16 decimal digits. Or, you could write your own code, which might be less difficult than you may think. (Of course, I don't know how hard you think that is. This is indeed a conundrum.)
Finally, many such questions really don't ask to compute an actual sum, but they often ask for something like a remainder with respect to some given integer modulus. In fact, that is very doable in double precision arithmetic. In the case of your code, it seems you are actually computing and saving the numbers themselves, so it would not help here.
  3 Commenti

Accedi per commentare.

Più risposte (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by