# Scipy Welch's gives different first element

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


testing:

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?

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