I've re-implemented Welch's method and want to compare it to scipy.signal.welch. However, the first two and last elements of the resulting array are different.

My Welchs function (not optimized and without taper, as this is not the issue here)

import numpy as np
import scipy

def welchs(signal, nperseg=512, noverlap=0):
    taper = np.ones(nperseg) # assume boxcar taper for simplicity
    scale = 1.0 / (1 * (taper*taper ).sum()/2)
    siglen = signal.shape[-1]
    step = nperseg - noverlap
    fft_segments = []
    for i in range(0, siglen, step):
        if i+nperseg>siglen: 
            print(i+nperseg, '>', siglen)
        segment = signal[i:i+nperseg]
        w = np.fft.rfft(segment)
    fft_segments = np.array(fft_segments)
    fft_mean = np.mean(fft_segments, 0)
    return fft_mean * scale


signal = np.sin(np.linspace(0,512, 1024))

w1 = welchs(signal, nperseg=512, noverlap=0)
_,w2 = scipy.signal.welch(signal, nperseg=512, noverlap=0, detrend=False, window='boxcar')
np.testing.assert_almost_equal(w1,w2) # -> 0.7% mismatch, 2 elements

All elements of w1 and w2 are the same except the first and the last.

Can anyone explain to me what my implementation might be missing?

  • $\begingroup$ Is there a factor of $2$ (or $1/2$, respectively) between w1 and w2? $\endgroup$ – applesoup Jan 28 at 15:45
  • $\begingroup$ Yes, that seems to be the case, but only for the first elements $\endgroup$ – skjerns Jan 31 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.