# Set up grid and differentiation matrix:
N = 24; h = 2*pi/N; x = h*arange(1,N+1);
# wave numbers
ik = 1j*arange(0,N//2+1)
# Differentiation of a hat function:
v = maximum(0.0,1.0-abs(x-pi)/2.0)
v_hat = rfft(v)
w_hat = ik * v_hat; w_hat[N//2] = 0.0
w = irfft(w_hat)
figure(figsize=(10,6))
subplot(3,2,1)
plot(x,v,'.-')
axis([0, 2*pi, -.5, 1.5])
title('function')
subplot(3,2,2)
plot(x,w,'.-')
axis([0, 2*pi, -1, 1])
title('spectral derivative')
# Differentiation of exp(sin(x)):
v = exp(sin(x)); vprime = cos(x)*v;
v_hat = rfft(v)
w_hat = ik * v_hat; w_hat[N//2] = 0.0
w = irfft(w_hat)
subplot(3,2,3)
plot(x,v,'.-')
axis([0, 2*pi, 0, 3])
subplot(3,2,4)
plot(x,w,'.-')
axis([0, 2*pi, -2, 2])
error = norm(w-vprime,inf)
text(1.5,1.4,"max error="+str(error));