% DEMO:         APPROXIMATING exp(j*theta)
%
% Program:      app_expj.m
% Written by:   
% For:          EE 311
%               Demo for Computer Lab 1
% Date:         6-7-2001
% Purpose:      This program approximates the complex number
%               exp(j*theta) for a user input of theta.
%               Euler's Definition and Taylor Series approximations
%               are calculated and both results are plotted on the
%               complex plane.
% Notes:        You can enter values like pi/4, and 2*pi/3 
%               for your theta in radians when you run the program.
clear all, hold off, clf reset, close all

j=sqrt(-1);
circle=exp(j*2*pi*[0:200]/200);
s=1; fact=1; geo_sum=0;             % Initialize variables
disp('This Program Approximates exp(j*theta)')
theta=input('Enter the value of theta in radians: ');
m=input('Enter the number of terms use in the approximations: ');
x=j*theta;

% Euler's Definition for approximating exp(j*theta)
% calculated for n = 1 to m
for n=1:m
    approx1(n)=(1+x/n)^n;           % Approximation #1
end

% Taylor Series expansion for approximating exp(j*theta)
% This sum runs from 0 to m-1
for n=1:m                           % Approximation #2
    if n~=1
        fact=fact*(n-1);            % Hold current n!
    end
    geo_sum=geo_sum+x^(n-1)/fact;   % Calculate geometric sum
    approx2(n)=geo_sum;             % Save n-th term of 
end                                 % Taylor Series Expansion

% Plotting the results
% Euler's Definition is plotted using red x's
% Taylor Series approximation plotting using blue lines

% Cartesian Plot
axis('square')
hold on
s=['Cartesian Plot of an ' num2str(m) '-term approximation of '];
s=[s 'exp(j*' num2str(theta) ')'];
title(s)

plot(real(circle),imag(circle),'-k')
plot(real(approx1),imag(approx1),'xr',real(approx2),imag(approx2),'-b')
grid

% Polar Plot
figure
polar(angle(circle),abs(circle),'-k')
hold on
s=['Polar Plot of an ' num2str(m) '-term approximation of '];
s=[s 'exp(j*' num2str(theta) ')'];
title(s)

polar(angle(approx1),abs(approx1),'xr')
polar(angle(approx2),abs(approx2),'-b')
axis('square')
figure(gcf)