%% Exercise 6, approx of \pi, area of ellipse
% Monte Carlo simulation
% HA, 4.12.2018
%% (a) Draw square and circle (dartboard) inside.

close all;format short;format compact % squeeze off extra blank lines
t = linspace(0,2*pi);
x = cos(t);y = sin(t);
plot(x,y,[1 1 -1 -1 1 ], [-1 1 1 -1 -1]);
axis([-1.5 1.5 -1.5 1.5])
axis square;shg

%
%% (b) Draw points (throw darts)
% n = 10000 % Nr. of "darts", start with "small"

n = 100000; % Increase n
X = 2*rand(n,1)-1; % Random x-coords on (-1,1).
Y = 2*rand(n,1)-1; % Random y-coords on (-1,1).

%

in = (X.^2+Y.^2)<=1; % Logical indices for points inside circle 
out=~in;
hold on
plot(X(in),Y(in),'r.',X(out),Y(out),'k.');shg
Nin=sum(in)   % in is a logical vector sum(in):nr.of ones. 
%

%
%% Display in 2 ways:
% 1)

disp('Display using disp: ')
disp(' ')
disp(['  4*inside/n  ' '   pi'])
disp([4*Nin/n, pi])
disp(' ')
% 2)
disp('Display using fprintf:')
disp(' ')
fprintf('4*hits/total = %1.6f pi = %1.6f\n',4*Nin/n,pi);
hold off

%
%% (c) Ellipse

help myAellipse

%

type myAellipse
%

%

[Aappr,Atrue] = myAellipse(2,1,10000)
[Aappr,Atrue] = myAellipse(2,1,100000)
%

%
%% Notes:
% Some student solutions just used an approximation for \pi obtained in the circle case to compute  \pi a b. This was a little too much of a short cut. Anyway, we were quite generous in evaluation.
% Another problem was far too small value of nr. of points leading to unnecessarily poor approximations. One can get easily about 3 correct digits, but hardly many more.
%% Some advanced Matlab-functions
% There was at least one student who referred to the functions below:
% nnz Matlab has a built-in function "number of nonzeros". In the basic course we prefer teaching the "basic core" Matlab thinking
% polyarea This is an advanced function to compute numerically the area inside a polygon. One student (cleverly) realized that Matlab's circle, ellipse etc. are in fact polygons. Anyway sticking to basics is again preferred. How many of you would fluently read and understand the code of polyarea as compared to the method of logical indexing.