% ECE 248, UCSB, Homework 1 P1.7c SOLUTION (due Oct. 22, 2010)
% Katie Byl
%
% Betting an amount proportional to your advantage time your bankroll
% is known as "Kelly" betting.  This script calculates all required
% plots and values for part c of the problem.
fprintf('ECE 248, UCSB, Homework 1 P1.7 c) SOLUTION. Fall 2010.\n\n')
clear all; format compact  % format compact yields single-spaced text

pwin = .55;  % chance of winning
plose = 1-pwin;
Fwin = 1.1;  % fractional change in bankroll, if you WIN
Flose = 2-Fwin;  % fractional change in bankroll, if you LOSE

N = 100; r=zeros(1,N+1); q=zeros(1,N+1); % pre-allocate
for n=0:N
    r(N+1-n) = (Flose)^(n)*Fwin^(N-n);  % "r" is the Fractional AMT of money at end
    % "q" is the PROBABILITY this would happen:
    q(N+1-n) = (1-pwin)^(n)*pwin^(N-n)*prod(1:N)/(prod(1:(N-n))*prod(1:n));
    % q(N+1-n) = (1-pwin)^(n)*pwin^(N-n)*exp(sum(log(1:N))-(sum(log(1:(N-n)))+sum(log(1:n))));
    % The form commented in the line above can avoid "overflow" issues...
end

% PLOT the results, both on a linear plot and a semilogx plot:
figure(3); clf; 
for n=1:2
    subplot(2,1,n)
    if n==1
        plot(r,cumsum(q),'b.-') % Note: cumsum = .5 at the median value:
        axis([0 10 0 1])
    else
        semilogx(r,cumsum(q),'b.-')
        axis([.01 100 0 1])
    end
    xlabel('Fraction of bankroll')
    ylabel('CDF that this would occur')
    grid on
    title('HW1p7-c : Cumulative distribution fn, after 100 bets (Kelly betting)')
end

% Finally, print required outputs to the MATLAB workspace:
fi = find(cumsum(q)<=.9);
MEDIAN = interp1(cumsum(q(fi)),r(fi),.5)
[ai,bi] = max(q);  % find where max of fx(x) is by SORTING
MODE = r(bi)  % This is where the pdf is highest: the most likely value
EV = sum(r.*q)  % Expected value (aka mean)
MSV = sum((r.^2).*q)  % mean square value
VAR = MSV - EV^2   % variance

% ===== END OF FILE =====