Total Harmonic Distortion (THD) in Power Electronics - Time & Space Complexity
When calculating Total Harmonic Distortion (THD), we want to know how the work needed grows as we include more harmonics.
We ask: How does the calculation time increase when we analyze more harmonic frequencies?
Analyze the time complexity of the following code snippet.
// Calculate THD by summing squares of harmonic amplitudes
function calculateTHD(harmonics) {
let sumSquares = 0;
for (let i = 1; i < harmonics.length; i++) {
sumSquares += harmonics[i] * harmonics[i];
}
return Math.sqrt(sumSquares) / harmonics[0];
}
This code calculates THD by looping through all harmonic amplitudes except the fundamental, summing their squares, then dividing by the fundamental amplitude.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the harmonic amplitudes array once.
- How many times: Exactly once for each harmonic beyond the first (fundamental).
As the number of harmonics increases, the number of operations grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 9 additions and multiplications |
| 100 | 99 additions and multiplications |
| 1000 | 999 additions and multiplications |
Pattern observation: The work grows in a straight line as more harmonics are added.
Time Complexity: O(n)
This means the time to calculate THD increases proportionally with the number of harmonics analyzed.
[X] Wrong: "Calculating THD takes the same time no matter how many harmonics we include."
[OK] Correct: Each additional harmonic adds more calculations, so the time grows with the number of harmonics.
Understanding how calculation time grows with input size shows you can analyze and explain performance, a useful skill in many technical discussions.
"What if we only calculated THD using every other harmonic? How would the time complexity change?"