Commit 647d8d8
committed
Fix IndexError in THD() for low/fractional fundamental frequencies
THD() computes the harmonic count from the continuous fundamental
(num_harmonics = int((fs/2)/frequency)) but indexes each harmonic with the
rounded fundamental bin i = int(round(frequency*N/fs)). When the fractional bin
rounds up, i * num_harmonics overshoots the rfft length len(f) = N//2+1, so the
last harmonic's bin lands past Nyquist and f[i*h] is out of bounds. For a low
fundamental (e.g. THD(sig, 12000, freq=5.994): i=6, num_harmonics=1001,
i*1001=6006 > 6001) this raises IndexError.
Guard the index and break the loop once i*h reaches len(f). A harmonic at bin
>= len(f) is above the Nyquist frequency and cannot exist in the sampled
spectrum, so it must be excluded; break (not continue) is correct because h
increases monotonically. Harmonics in range are summed exactly as before, so
results for normal signals are unchanged.
Fixes #38.1 parent 6bfa59b commit 647d8d8
2 files changed
Lines changed: 19 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
149 | 149 | | |
150 | 150 | | |
151 | 151 | | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
| 163 | + | |
152 | 164 | | |
153 | 165 | | |
154 | 166 | | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
232 | 232 | | |
233 | 233 | | |
234 | 234 | | |
| 235 | + | |
| 236 | + | |
| 237 | + | |
| 238 | + | |
| 239 | + | |
| 240 | + | |
| 241 | + | |
235 | 242 | | |
236 | 243 | | |
237 | 244 | | |
| |||
0 commit comments