%
% test the accuracy of Discrete and Continuous Fourier Approximations
% Written by Ming Gu for Math 128B, Spring 2010
%
%%
%% Fourier approximations are lousy for non-smooth/non-periodic functions.
%%
n = 1024;
x = -pi + 2*pi/n*(0:n-1)';
y = abs(sin(x));
[a,b] = DLS(y);
z = EvalFourier(a,b,x);
disp('...');
disp('Fourier approximations are lousy for non-smooth/non-periodic functions.')
disp(['Testing function |sin(x)| at ', num2str(n), ' points.']);
disp(['Error in recovering original function value = ', num2str(norm(y-z))]);
x1 = (2*pi)*(rand(n,1)-0.5);
y1 = abs(sin(x1));
z1 = EvalFourier(a,b,x1);
disp(['Maximum Error in approximation at random points = ', num2str(max(abs(y1-z1)))]);

%%
%% Fourier approximations are very good for periodic smooth functions.
%%
disp('...');
disp('Fourier approximations are very good for periodic smooth functions.')
n = 20;
x = -pi + 2*pi/n*(0:n-1)';
y = exp(sin(x));
[a,b] = DLS(y);
z = EvalFourier(a,b,x);
disp(['Testing function exp(sin(x)) at ', num2str(n), ' points.']);
disp(['Error in recovering original function value = ', num2str(norm(y-z))]);
x1 = (2*pi)*(rand(n,1)-0.5);
y1 = exp(sin(x1));
z1 = EvalFourier(a,b,x1);
disp(['Maximum Error in approximation at random points = ', num2str(max(abs(y1-z1)))]);

%%
%% Now perform contiuous Fourier approximation for the same smooth functions.
%%
disp('...');
disp('Contiuous Fourier approximation for the same smooth functions.');
disp('Working ...');
myfunc1 = inline('exp(sin(x)).*cos(k*x)','x','k');
myfunc2 = inline('exp(sin(x)).*sin(k*x)','x','k');
tol = 1e-11;
m = n/2;
a2 = zeros(m+1,1);
for k=1:m+1
   a2(k) = quad(@(x)myfunc1(x,k-1),-pi,pi,tol);
end
a2(1)   = a2(1)/(2*pi);
a2(2:m) = a2(2:m)/pi;
b2 = zeros(m-1,1);
for k=1:m-1
   b2(k) = quad(@(x)myfunc2(x,k),-pi,pi,tol);
end
b2 =b2/pi;
z2 = EvalFourier(a2,b2,x1);
disp(['Maximum Error in continuous approximation = ', num2str(max(abs(y1-z2)))]);
disp(['Difference in a coefficients = ', num2str(norm(a2-a))]);
disp(['Difference in b coefficients = ', num2str(norm(b2-b))]);

