Determine the first digit of each element of Fibonacci Sequence.

3 views (last 30 days)
Using your favorite programing language (Matlab) compute the first 1000 elements of the Fibonacci sequence f(n) =f(n−1) +f(n−2) where f(1) = f(2) = 1. Determine the first digit of each element .
Here, I can find the 1000 element easily using the Fibonacci function. But I am not sure how to the get the first digit of the fist 1000 element. Any suggestion will be appriciated. Thanks
  3 Comments
mouaz chowdhury
mouaz chowdhury on 8 Sep 2019
I was thinking about doing this.
n = 1: 1000;
fibonacci(n);
Shouldnt this work?
Walter Roberson
Walter Roberson on 9 Sep 2019
You can use 1o^floor(log10(x)) to get a number between 1 and (10-eps) ...

Sign in to comment.

Accepted Answer

David Hill
David Hill on 8 Sep 2019
str2double(cellfun(@(x)x(1),arrayfun(@(x)num2str(x),fibonacci(1:1000),'UniformOutput',false),'UniformOutput',false));
I think the above provides you with an array of the first digits of the fibonacci numbers up to 1000.
  2 Comments
Rik
Rik on 8 Sep 2019
suggested=str2double(cellfun(@(x)x(1),arrayfun(@(x)num2str(x),fibonacci(1:1000),'UniformOutput',false),'UniformOutput',false));
fib=zeros(1,1000);
fib(1:2)=1;
out=fib;
for n=3:1000
fib(n)=fib(n-1)+fib(n-2);
tmp=sprintf('%.5e',fib(n));
out(n)=tmp(1)-'0';
end
if any(out-suggested)
disp('at least one method is wrong')
else
disp('both are correct, or wrong in the same places')
end
There is no checking for potential issues like Walter suggests, but is seems the symbolic toolbox handles it well enough. Or both have an error in the same place.
Walter Roberson
Walter Roberson on 9 Sep 2019
Futher testing with symbolic calculations shows that using numeric approximation to double gives the same first digit as for exact calculations.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!