How to calculate first 100 Fibonacci numbers?
조회 수: 7 (최근 30일)
이전 댓글 표시
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
댓글 수: 0
답변 (4개)
Image Analyst
2017년 10월 26일
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
댓글 수: 0
Walter Roberson
2017년 10월 26일
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
댓글 수: 0
Maruf Ahamed
2018년 4월 17일
편집: Maruf Ahamed
2018년 4월 17일
% 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
Walter Roberson
2018년 4월 17일
This does not appear to solve the issue of limited precision of double() variables that will start happening at about 74.
philip
2023년 6월 14일
% 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);
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Number Theory에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!