How to calculate first 100 Fibonacci numbers?

10 views (last 30 days)
Drew Clements
Drew Clements on 26 Oct 2017
Answered: philip on 14 Jun 2023
clear
n(1) = 1;
n(2) = 1;
k = 3;
while k <= 100
n(k) = [n(k-2) + n(k-1)];
k = k + 1;
end
How do you get an answer that isn't this?
n =
1.0e+20 *
Columns 1 through 9
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 10 through 18
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 19 through 27
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 28 through 36
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 37 through 45
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 46 through 54
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 55 through 63
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 64 through 72
0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000
Columns 73 through 81
0.0000 0.0000 0.0000 0.0000 0.0001 0.0001 0.0001 0.0002 0.0004
Columns 82 through 90
0.0006 0.0010 0.0016 0.0026 0.0042 0.0068 0.0110 0.0178 0.0288
Columns 91 through 99
0.0466 0.0754 0.1220 0.1974 0.3194 0.5168 0.8362 1.3530 2.1892
Column 100
3.5422

Answers (4)

Image Analyst
Image Analyst on 26 Oct 2017
Try removing the semicolon from this line
n(k) = [n(k-2) + n(k-1)];
Or display n with fprintf():
fprintf('%g, ', n);
Or put this at the beginning of your code
format compact
format short g

Walter Roberson
Walter Roberson on 26 Oct 2017
Giving the command
format long g
would help. You would still run into format problems, starting at about #74, as the numbers start to exceed the available resolution of double precision numbers.
Changing the first line to
n(1) = uint64(1);
also helps. You will notice, though, that the last 7 entries are all the same, 18446744073709551615, which is the maximum number that can be expressed as uint64.
Changing the first line to
n(1) = sym(1);
solves the problem, if you have the Symbolic Toolbox

Maruf Ahamed
Maruf Ahamed on 17 Apr 2018
Edited: Maruf Ahamed on 17 Apr 2018
 % code
  you can try this:
clc
clear all
n=input('n=')
j=0;
c=1;
h=2;
d(1)=1;
for i=1:n
   k=c+j;
   d(h)=k;
   h=h+1;
   j=k;
   c=c+j;
   d(h)=c;
   h=h+1;
end
 d  
  1 Comment
Walter Roberson
Walter Roberson on 17 Apr 2018
This does not appear to solve the issue of limited precision of double() variables that will start happening at about 74.

Sign in to comment.


philip
philip on 14 Jun 2023
% Initialize variables
fibonacci = zeros(1, 100);
fibonacci(1) = 0;
fibonacci(2) = 1;
% Generate Fibonacci sequence
for i = 3:100
fibonacci(i) = fibonacci(i-1) + fibonacci(i-2);
end
% Display Fibonacci sequence
disp(fibonacci);

Community Treasure Hunt

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

Start Hunting!