MATLAB: Energy of a signal in t and f domain

digital signal processingenergyfftsignalspectrum

The energy of a signal is expected to be the same in t and f domain.
n = 1e4;
dx = 0.25;
x = rand(n,1) -0.5;
ex = sum(x.^2) *dx; % energy in t domain
y = fft(x);
fs = 1/dx;
df = fs/n;
ya = abs(y);
ey = sum(ya.^2) *df; % energy in f domain
but from the code, ey/ex=16, exactly the squared fs.
what's the problem?

Best Answer

I found the solution myself.
Normalizing spectral amplitude by fs will work.
But I don't know why to do this.
Related Question