Lecture 2: Logic Gates & Fibonacci Numbers

Date: 09/05/2017, Tuesday

In [1]:
format compact

Logic gates

nand gate

In [2]:
nand = @(a,b) ~(a&b)
nand =
  function_handle with value:
    @(a,b)~(a&b)
In [3]:
nand(1,1) % test if it works
ans =
  logical
   0

build “not” gate from “nand” gate

In [6]:
my_not = @(a) nand(a,a) % "not" is a built-in function so we use my_not to avoid conflicts
my_not =
  function_handle with value:
    @(a)nand(a,a)
In [7]:
boolean_print_TT_fn(my_not,1)
_____
a|out
0|1
1|0

Why nand(a,a) means not:

  1. and(a,a) = a, no matter a is 0 or 1
  2. nand(a,a) = not and(a,a) = not a

Fibonacci Sequence

generate Fibonacci sequences

In [8]:
%%file fib_fn.m
function F = fib_fn(n)

    F = zeros(1,n);
    F(1)=1;
    F(2)=1;
    for j=3:n
        F(j)=F(j-1)+F(j-2);
    end

end
Created file '/Users/zhuangjw/Research/Computing/personal_web/AM111/docs/fib_fn.m'.
In [9]:
fib_fn(10)
ans =
     1     1     2     3     5     8    13    21    34    55

Compare with the built-in function fibonacci( )

In [10]:
fibonacci(1:10)
ans =
     1     1     2     3     5     8    13    21    34    55

golden ratio

In [11]:
golden_ratio = (sqrt(5)+1)/2 % true value
golden_ratio =
    1.6180

\(F_n/F_{n-1}\) Converges to the golden ratio

In [12]:
F = fib_fn(10);
F_ratio = F(2:end)./F(1:end-1)
F_ratio =
  Columns 1 through 7
    1.0000    2.0000    1.5000    1.6667    1.6000    1.6250    1.6154
  Columns 8 through 9
    1.6190    1.6176
In [13]:
%plot --size 400,300
hold on
plot(F_ratio,'-o')
plot([0,10],[golden_ratio,golden_ratio])
_images/lecture2_logics_fib_23_0.png