Skip to content

Commit 88cf102

Browse files
feat: add goertzel algorithm (#176)
* add goertzel algorithm * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * split declaration from implementation * Update TestGoertzelAlgorithm.cpp --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent bb43d57 commit 88cf102

12 files changed

Lines changed: 366 additions & 168 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
1616

1717
| Category | Description |
1818
|--------------------------------------------------------------------|----------------------------------------------------------------------|
19-
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors, Convolution & Correlation |
19+
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors, Convolution & Correlation, Goertzel Algorithm |
2020
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
2121
| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |

‎ROADMAP.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@ Difficulty legend:
2727

2828
| # | Component | Target module | Difficulty |
2929
|----|------------------------------------------------------|---------------------------|------------|
30-
| 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ |
3130
| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ |
3231
| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ |
3332
| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ |

‎doc/analysis/GoertzelAlgorithm.md‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Goertzel Algorithm
2+
3+
## Overview & Motivation
4+
5+
When a system needs to detect or measure a single known frequency — a DTMF touch-tone, a pilot sync tone, mains-hum, or a narrowband alarm — computing a full FFT wastes every cycle spent on bins that will never be read. The Goertzel algorithm computes exactly one DFT bin using a second-order recurrence that processes samples one at a time, requiring no input buffer and no twiddle-factor table. On the smallest microcontrollers with a few hundred bytes of RAM, this distinction is decisive.
6+
7+
## Mathematical Theory
8+
9+
### Core Definitions
10+
11+
Let $x[n]$, $n = 0, \ldots, N-1$, be a block of $N$ real samples. The DFT coefficient at bin $k$ is:
12+
13+
$$X[k] = \sum_{n=0}^{N-1} x[n]\, e^{-j2\pi kn/N}$$
14+
15+
Define the resonator coefficient:
16+
17+
$$c = 2\cos\!\left(\frac{2\pi k}{N}\right)$$
18+
19+
### Derivation
20+
21+
The DFT sum can be reorganised as the output of a single-pole IIR filter evaluated at $n = N$. Introduce the auxiliary sequence:
22+
23+
$$s[n] = x[n] + c\,s[n-1] - s[n-2], \quad s[-1] = s[-2] = 0$$
24+
25+
After $N$ steps the DFT bin follows from the final two state values:
26+
27+
$$X[k] = s[N-1] - s[N-2]\,e^{-j2\pi k/N}$$
28+
29+
Separating real and imaginary parts:
30+
31+
$$\operatorname{Re}\{X[k]\} = s[N-1] - s[N-2]\cos\!\left(\tfrac{2\pi k}{N}\right)$$
32+
33+
$$\operatorname{Im}\{X[k]\} = s[N-2]\sin\!\left(\tfrac{2\pi k}{N}\right)$$
34+
35+
The magnitude can be obtained without the final trigonometric products using the identity:
36+
37+
$$|X[k]|^2 = s[N-1]^2 + s[N-2]^2 - c\,s[N-1]\,s[N-2]$$
38+
39+
so $|X[k]| = \sqrt{s[N-1]^2 + s[N-2]^2 - c\,s[N-1]\,s[N-2]}$, saving two multiplies on the hot path.
40+
41+
### Frequency-to-Bin Mapping
42+
43+
A physical frequency $f_t$ sampled at $f_s$ maps to bin:
44+
45+
$$k = \operatorname{round}\!\left(\frac{f_t}{f_s}\,N\right)$$
46+
47+
Frequency resolution is $\Delta f = f_s / N$.
48+
49+
## Complexity Analysis
50+
51+
| Case | Time | Space | Notes |
52+
|------------|--------|--------|-----------------------------------------|
53+
| Per sample | $O(1)$ | $O(1)$ | One multiply, two adds, no table lookup |
54+
| Full block | $O(N)$ | $O(1)$ | Two state words; trig only at block end |
55+
56+
For $B$ bins of interest the total cost is $O(BN)$. An FFT computing all $N$ bins costs $O(N\log N)$, so the Goertzel approach is cheaper when $B \ll \log_2 N$ — typically $B \le 4$ for a 256-point transform.
57+
58+
## Step-by-Step Walkthrough
59+
60+
Consider $N = 4$, $k = 1$, $x = [1, 0, -1, 0]$.
61+
62+
$c = 2\cos(\pi/2) = 0$
63+
64+
| $n$ | $x[n]$ | $s[n] = x[n] + 0\cdot s[n-1] - s[n-2]$ |
65+
|-----|--------|----------------------------------------|
66+
| 0 | 1 | $1 + 0 - 0 = 1$ |
67+
| 1 | 0 | $0 + 0 - 1 = -1$ |
68+
| 2 | -1 | $-1 + 0 - 0 = -1$ (note: $s[-1]=0$) |
69+
| 3 | 0 | $0 + 0 - (-1) = 1$ |
70+
71+
$\cos(2\pi/4) = 0$, $\sin(2\pi/4) = 1$
72+
73+
$\operatorname{Re}\{X[1]\} = 1 - (-1)\cdot 0 = 1$
74+
75+
$\operatorname{Im}\{X[1]\} = (-1)\cdot 1 = -1$
76+
77+
Direct DFT check: $X[1] = 1 - j$. Matches.
78+
79+
## Pitfalls & Edge Cases
80+
81+
The recurrence pole sits exactly on the unit circle, making the filter marginally stable. Error accumulates with each block if `Reset` is not called between blocks. The algorithm is designed for finite, bounded blocks of exactly $N$ samples.
82+
83+
Choosing $N$ such that the target tone lands near an integer bin minimises spectral leakage. A mismatch of half a bin can reduce the apparent magnitude by several decibels. Window functions do not apply here because the Goertzel filter already selects one bin; applying a window changes the effective DFT kernel.
84+
85+
The DC bin ($k = 0$) and the Nyquist bin ($k = N/2$) are purely real; their imaginary output is zero by symmetry.
86+
87+
## Variants & Generalizations
88+
89+
The magnitude-squared form $s_1^2 + s_2^2 - c\,s_1 s_2$ avoids the square root when only power detection (threshold comparison) is needed, saving a transcendental call on platforms without hardware `sqrt`.
90+
91+
When several tones must be tracked simultaneously, one independent Goertzel instance per tone runs in $O(BN)$ total with $O(B)$ state — still far cheaper than an FFT for small $B$.
92+
93+
A sliding Goertzel variant updates one sample at a time by subtracting the oldest sample, giving a continuous output at the cost of maintaining an input ring buffer; this trades $O(1)$ memory for $O(N)$ memory and is outside the scope of the no-heap constraint here.
94+
95+
## Applications
96+
97+
- DTMF decoding (telephony, industrial keypads)
98+
- Sync-tone and pilot-tone detection in radio links
99+
- Mains-frequency monitoring (50/60 Hz hum)
100+
- Single-bin power spectral estimation in embedded monitors
101+
- Lock-in detection for narrow-band sensor readout
102+
103+
## Connections to Other Algorithms
104+
105+
The Goertzel algorithm computes exactly the same result as one bin of the DFT computed by the Cooley-Tukey FFT (`FastFourierTransform`), but limits the computation to that single bin. When all $N$ bins are required simultaneously, the FFT is always faster. `PowerDensitySpectrum` builds on the FFT for broadband spectral estimation. `SignalDetectors` provides simpler, non-frequency-selective detectors (peak hold, RMS) that cost even less per sample.
106+
107+
## References & Further Reading
108+
109+
- G. Goertzel, "An Algorithm for the Evaluation of Finite Trigonometric Series," *American Mathematical Monthly*, 65(1), 34–35, 1958.
110+
- A. V. Oppenheim and R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Prentice Hall, 2009, §8.1.
111+
- P. Mock, "Add DTMF Generation and Decoding to DSP-µP Designs," *EDN*, March 1985 (practical embedded application of Goertzel).

‎doc/analysis/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ Signal analysis algorithms for frequency-domain decomposition and spectral estim
1010
| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method |
1111
| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT |
1212
| [Signal Detectors](SignalDetectors.md) | Peak hold, zero-crossing counter, and RMS envelope detectors for real-time signal monitoring |
13+
| [Goertzel Algorithm](GoertzelAlgorithm.md) | Single-bin DFT via a second-order recurrence for O(N) tone detection with O(1) memory |
1314

1415
## Sub-domains
1516

‎numerical/analysis/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@ target_sources(numerical.analysis PRIVATE
1616
DiscreteCosineTransform.hpp
1717
FastFourierTransform.hpp
1818
FastFourierTransformRadix2Impl.hpp
19+
GoertzelAlgorithm.hpp
1920
PowerDensitySpectrum.hpp
2021
SignalDetectors.hpp
2122
)
2223

2324
numerical_add_coverage_sources(numerical.analysis
2425
ConvolutionCorrelation.cpp
2526
FastFourierTransformRadix2Impl.cpp
27+
GoertzelAlgorithm.cpp
2628
PowerDensitySpectrum.cpp
2729
SignalDetectors.cpp
2830
)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#include "numerical/analysis/GoertzelAlgorithm.hpp"
2+
3+
namespace analysis
4+
{
5+
template class GoertzelAlgorithm<float>;
6+
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
#pragma once
2+
3+
#if defined(__GNUC__) || defined(__clang__)
4+
#pragma GCC optimize("O3", "fast-math")
5+
#endif
6+
7+
#include "numerical/math/CompilerOptimizations.hpp"
8+
#include "numerical/math/ComplexNumber.hpp"
9+
#include <cmath>
10+
#include <cstddef>
11+
#include <numbers>
12+
#include <type_traits>
13+
14+
namespace analysis
15+
{
16+
template<typename T>
17+
class GoertzelAlgorithm
18+
{
19+
static_assert(std::is_floating_point_v<T>, "GoertzelAlgorithm supports floating-point types only");
20+
21+
public:
22+
GoertzelAlgorithm(std::size_t k, std::size_t blockLength);
23+
GoertzelAlgorithm(T targetHz, T sampleHz, std::size_t blockLength);
24+
25+
OPTIMIZE_FOR_SPEED void Push(T x);
26+
bool Ready() const;
27+
math::Complex<T> Result() const;
28+
T Magnitude() const;
29+
void Reset();
30+
31+
static T Coefficient(std::size_t k, std::size_t blockLength);
32+
33+
private:
34+
T coeff;
35+
T cosine;
36+
T sine;
37+
std::size_t blockSize;
38+
T s1;
39+
T s2;
40+
std::size_t sampleCount;
41+
};
42+
43+
template<typename T>
44+
GoertzelAlgorithm<T>::GoertzelAlgorithm(std::size_t k, std::size_t blockLength)
45+
: coeff{ T{ 2 } * std::cos(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)) }
46+
, cosine{ std::cos(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)) }
47+
, sine{ std::sin(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)) }
48+
, blockSize{ blockLength }
49+
, s1{ T{ 0 } }
50+
, s2{ T{ 0 } }
51+
, sampleCount{ 0 }
52+
{}
53+
54+
template<typename T>
55+
GoertzelAlgorithm<T>::GoertzelAlgorithm(T targetHz, T sampleHz, std::size_t blockLength)
56+
: GoertzelAlgorithm(
57+
static_cast<std::size_t>(targetHz / sampleHz * static_cast<T>(blockLength) + T{ 0.5 }),
58+
blockLength)
59+
{}
60+
61+
template<typename T>
62+
OPTIMIZE_FOR_SPEED void GoertzelAlgorithm<T>::Push(T x)
63+
{
64+
T s0{ x + coeff * s1 - s2 };
65+
s2 = s1;
66+
s1 = s0;
67+
++sampleCount;
68+
}
69+
70+
template<typename T>
71+
bool GoertzelAlgorithm<T>::Ready() const
72+
{
73+
return sampleCount >= blockSize;
74+
}
75+
76+
template<typename T>
77+
math::Complex<T> GoertzelAlgorithm<T>::Result() const
78+
{
79+
T real{ s1 - s2 * cosine };
80+
T imag{ s2 * sine };
81+
return math::Complex<T>{ real, imag };
82+
}
83+
84+
template<typename T>
85+
T GoertzelAlgorithm<T>::Magnitude() const
86+
{
87+
return std::sqrt(s1 * s1 + s2 * s2 - coeff * s1 * s2);
88+
}
89+
90+
template<typename T>
91+
void GoertzelAlgorithm<T>::Reset()
92+
{
93+
s1 = T{ 0 };
94+
s2 = T{ 0 };
95+
sampleCount = 0;
96+
}
97+
98+
template<typename T>
99+
T GoertzelAlgorithm<T>::Coefficient(std::size_t k, std::size_t blockLength)
100+
{
101+
return T{ 2 } * std::cos(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength));
102+
}
103+
}
104+
105+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
106+
namespace analysis
107+
{
108+
extern template class GoertzelAlgorithm<float>;
109+
}
110+
#endif

‎numerical/analysis/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ target_sources(numerical.analysis_test PRIVATE
1212
TestConvolutionCorrelation.cpp
1313
TestDiscreteCosineTransform.cpp
1414
TestFastFourierTransformRadix2Impl.cpp
15+
TestGoertzelAlgorithm.cpp
1516
TestPowerDensitySpectrum.cpp
1617
TestSignalDetectors.cpp
1718
)

0 commit comments

Comments
 (0)