%% 5.19
expected = exp(-1);
n = 1;
approx = 0;
while abs(expected - approx) > 0.0001
    approx = (1 - 1 / n)^n;
    n = n + 1;
end
disp(sprintf('1/e = %f, approx = %.4f, n = %d', expected, approx, n))


%% 5.30
v = randi(21, [1, 5]) - 11;   % or v = randi([-10 10], [1 5])

% subtract 3 from each element
result = v;
for idx = 1:length(v)
    result(idx) = v(idx) - 3;
end

% count how many are positive
npos = 0;
for idx = 1:length(v)
    if v(idx) > 0
        npos = npos + 1;
    end
end

% absolute value of each element
result = v;
for idx = 1:length(v)
    if v(idx) < 0
        result(idx) = -v(idx);
    end
end

% maximum
maximum = -10;
for idx = 1:length(v)
    if v(idx) > maximum
        maximum = v(idx);
    end
end


%% 5.33
vec = [3 2 1 6 7];
newv = zeros(size(vec));
myprod = 1;
for i = 1:length(vec)
    myprod = myprod * vec(i);
    newv(i) = myprod;
end
newv
% notice that the ith element of newv is vec(1) * vec(2) * ... * vec(i)
% which is just the cumulative product
cumprod(vec)


%% 5.45

a = randi([0 9], [1 30]);
b = randi([0 9], [1 30]);
c = zeros(1, 31);           % tricky! a + b can be 31 digits long
carry = 0;
for idx = 30:-1:1
    tmp = a(idx) + b(idx) + carry;
    if tmp > 9
        tmp = tmp - 10;
        carry = 1;
    else
        carry = 0;
    end
    c(idx + 1) = tmp;
end
if carry == 1
    c(1) = 1;
end
[[0 a]' [0 b]' c']


%% 12.3
A = [15.94 15.98 15.94 16.16 15.86 15.86 15.90 15.88];
B = [15.96 15.94 16.02 16.10 15.92 16.00 15.96 16.02];

statsA = [mean(A) median(A) mode(A) std(A)]
statsB = [mean(B) median(B) mode(B) std(B)]

% the mean of B is closer to 16
% the standard deviation of B is smaller than that for A



