function hw2_02

echo off, clc
clear all

 Emin = 3;
 Emax = 10;
 
 i = 1;
 for n=Emin:Emax
   Err(i,1) = 2^n;
   Err(i,2) = Third_Diff_Galerkin( 2^n );
   i = i + 1;
 end;
 
 figure(1); loglog(Err(:,1), Err(:,2), '-x');
 
 
 
 
 
function [ w ] = Third_Diff_Galerkin( N )

% Setting up the grid
  dx = 2.0 * pi / N;
  X = (0.0:dx:(N-1)*dx);
  
% Evaluating the RHS function and transforming to Fourier space;
  Fr = fun( X );
  Ff = fft( Fr, N );
  
% Solving the problem
  for k=1:N/2
    k1 = k - 1;
    Uf(k) = - j * k1^3 * Ff(k);
% Reproducing the negative frequencies (note the index)    
    if ( k > 1 )
      Uf(N-k+2) = conj(Uf(k));
    end;
  end;
  
% the "oddball";  
  Uf(N/2+1) = 0.0;
  
% Transforming back to physical space
  Ur = real(ifft(Uf,N));

% Comparing with the analytical result;  
  w = norm( Ur - dfun( X ), inf );

  
  
% The function to be differentiated
function [ y ] = fun( x )
  
  y = 1.0  ./ ( 1.0 + sin(x/2.0).^2 );


% the analytical derivative
function [ dy ] = dfun( x )
  
  dy = ( 5.0*cos(1/2*x).^2 - 2 + cos(1/2*x).^4) .* cos(1/2*x) .* sin(1/2*x) ./ ...
       (16 - 32 * cos(1/2*x).^2 + 24 * cos(1/2*x).^4 - 8*cos(1/2*x).^6 ...
	+ cos(1/2*x).^8);
  
  
