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) break segment = signal[i:i+nperseg] w = np.fft.rfft(segment) fft_segments.append(np.abs(w)**2) 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
w2 are the same except the first and the last.
Can anyone explain to me what my implementation might be missing?