# p5.py - repetition of p4.py via FFT
#         Trefethen Spectral Methods in ...
#         For complex v, delete "real" commands.
#         Python/NumPy translation 12/14/12

from numpy import *
from numpy.fft import fft,ifft
from pylab import *

N = 24; h = 2*pi/N; x = h*arange(1,N+1)

# Differentiation of exp(sin(x)):
v = exp(sin(x)); vprime = cos(x)*v

v_hat = fft(v)
w_hat = 1j*hstack(( range(N/2),[0.],range(-N/2+1,0) ))*v_hat
w = real(ifft(w_hat))

subplot(1,2,1); plot(x,v,'.-',markersize=8)
xlim(0,2*pi); ylim(0.,3.); grid() 
subplot(1,2,2); plot(x,w,'.-',markersize=8)
xlim(0,2*pi); ylim(-2.,2.); grid() 
error = linalg.norm(w-vprime,inf)
text(2.2,1.4,'max error = '+str('%.4e' % error))

show()
