%Extra exercises from session 4. See the included PDF in the website.

% Evaluate sin_N(x) for x=pi/3. Let's do it by steps.
% First, define that N with some test value and create an auxiliary vector
% with 1,3,5, ... 
N = 10;
Aux1 = 1:2:N;

% We now get an auxiliary vector which is the powers of x:
Aux2 = (pi/3).^Aux1; %take a look at the output of this by removing the ;

% Now comes the tricky part: the alternating signs. To do this, we create
% another auxiliary vector that contains [1, -1, 1, -1, ...]. To do this we
% use our vast mathematical knowledge, so (-1)^2 = 1, (-1)^3 = -1 and so
% on. So:
Aux3 = (-1).^(2:(N/2+1)); % Again, remove the ; to see the result. That N/2 is
                      % because we want it to be the same size of Aux1. It
                      % starts with 2 and has a +1 at the end because we
                      % want the first element of Aux3 to be positive.
                      % An alternative is:
Aux3 = -(-1).^(1:(N/2));

% We now multiply element-wise Aux2 and Aux3, to get the alternating signs
% on Aux2. We will call the result Aux2 for simplicity:
Aux2 = Aux2.*Aux3;

% There's just one missing: dividing each element by the factorial (3!,
% 4!, etc). To calculate factorials in matlab, we use the function
% factorial(x). You can check "help factorial" to see how it works. We
% again use Aux1 to create a vector of factorials:
Aux4 = factorial(Aux1); %Matlab automatically creates the vector we need.

% We now divide Aux2 by the vector with factorials:
Aux2 = Aux2./Aux4;

% Finally, we just sum over Aux2:
sin_N = sum(Aux2);

% To compare with matlab's built-in function sin(x), we do
IsZeroSin = sin_N - sin(pi/3);

% Now, change the value N above until IsZero is zero:
display(IsZeroSin)

% The smallest you can get is -1.1102e-16. It's due to the way Matlab
% handles numbers.


%% Of course, it can all be done in one big command:
IsZeroSin = sum( (-(-1).^(1:(N/2))).*( (pi/3).^(1:2:N))./factorial(1:2:N))...
    -sin(pi/3); % The elipsis (...) allows us to continue the command in the
                % line. It's not necessary, though.
display(IsZeroSin)

%% And now for the cosine we'll do just the short version.
cos_N = sum( (-1).^(0:(N/2)) .* (pi/3).^(0:2:N)./factorial(0:2:N));

IsZeroCos = cos_N - cos(pi/3);
display(IsZeroCos)

