Skip to main content

Fourier Series

What is a Fourier series?​

A Fourier series is a way of writing a periodic signal, one that repeats every TT seconds, as a sum of sine and cosine waves. The waves are the harmonics: the fundamental frequency f0=1/Tf_0 = 1/T and its whole-number multiples 2f0,3f0,4f0…2f_0, 3f_0, 4f_0 \ldots Each harmonic has its own amplitude, given by the signal's Fourier coefficients.

A Fourier series grapher in a dark navy theme: the top chart shows a square wave and its partial sum with harmonics up to N = 15, rippling around the flat tops and overshooting at each jump; the bottom chart shows the harmonic amplitudes as stems at the odd harmonics 1, 3, 5 to 15, falling along a dashed 4 over pi n curve, with the left-out harmonics in grey

A square wave and its Fourier series with harmonics 1 to 15 (top), and the amplitude of each harmonic (bottom). Try the interactive version, where you can change the waveform and the number of harmonics.

Key takeaways
  • Any practical periodic signal is a sum of harmonics at f0,2f0,3f0…f_0, 2f_0, 3f_0 \ldots, plus a constant (its average).
  • The coefficients ana_n and bnb_n come from one integral each over one period. The trigonometric, amplitude–phase and complex forms all hold the same information.
  • A square wave contains only odd harmonics, with amplitude 4/(nπ)4/(n\pi). The smoother a waveform, the faster its harmonics shrink.
  • At a jump, a truncated series always overshoots by about 9% of the jump (the Gibbs phenomenon), however many terms you add.
  • For sampled data, the DFT of one period gives the coefficients: cn≈X[n]/Mc_n \approx X[n]/M.

How a Fourier series works​

A Fourier series is a recipe for a repeating waveform. The ingredients are fixed: a constant, then sine and cosine waves at one, two, three times the repeat frequency, and so on. Only the amounts change from one waveform to the next. Those amounts are the coefficients.

The picture below builds a square wave from its first three ingredients. Each one is a sine wave that fits a whole number of cycles into one period, so the sum repeats with the same period as the square wave.

Left: three sine waves over one period, harmonic 1 with amplitude 4/π ≈ 1.27, harmonic 3 with amplitude 4/(3π) ≈ 0.42 and harmonic 5 with amplitude 4/(5π) ≈ 0.25. Right: their sum, which follows a dashed square wave of +1 then −1 with three ripples on each flat part and a steep edge at the middle of the period

Three terms already give flat-ish tops and steep edges. Each extra odd harmonic adds a smaller, faster ripple that fills in more of the corners.

The coefficients are easy to find because sines and cosines at different harmonics are orthogonal: multiply two of them together and average over one period, and the result is zero unless they are the same harmonic. So to measure how much of harmonic nn a signal contains, multiply the signal by that harmonic's cosine (or sine) and average. Every other harmonic averages to zero and drops out.

The idea is named after Joseph Fourier, who used these series in his 1822 work on the flow of heat.

The Fourier series formula​

For a signal f(t)f(t) with period TT, write the fundamental angular frequency as ω0=2π/T=2πf0\omega_0 = 2\pi/T = 2\pi f_0. The trigonometric Fourier series is:

f(t)=a02+∑n=1∞(ancos⁡(nω0t)+bnsin⁡(nω0t))f(t) = \frac{a_0}{2} + \sum_{n=1}^{\infty} \Big( a_n \cos(n\omega_0 t) + b_n \sin(n\omega_0 t) \Big)

and its Fourier series coefficients are integrals over any one period:

an=2T∫0Tf(t)cos⁡(nω0t) dt,bn=2T∫0Tf(t)sin⁡(nω0t) dta_n = \frac{2}{T} \int_{0}^{T} f(t) \cos(n\omega_0 t)\, dt, \qquad b_n = \frac{2}{T} \int_{0}^{T} f(t) \sin(n\omega_0 t)\, dt
  • a0/2a_0/2 is the average value of the signal over a period (the DC level). Writing it as a0/2a_0/2 lets the same ana_n formula work for n=0n = 0.
  • ana_n measures the cosine part of harmonic nn, and bnb_n the sine part.
  • Harmonic nn has frequency nf0n f_0 hertz. For a 50 Hz waveform, harmonic 3 is at 150 Hz.
  • Stopping the sum at n=Nn = N gives the partial sum SN(t)S_N(t), which is what a graph or a computer actually draws.

Amplitude–phase form​

A cosine and a sine at the same frequency add up to one shifted cosine. So the series can also be written with one amplitude and one phase per harmonic:

f(t)=a02+∑n=1∞Ancos⁡(nω0t−φn),An=an2+bn2,φn=atan2⁡(bn,an)f(t) = \frac{a_0}{2} + \sum_{n=1}^{\infty} A_n \cos(n\omega_0 t - \varphi_n), \qquad A_n = \sqrt{a_n^2 + b_n^2}, \quad \varphi_n = \operatorname{atan2}(b_n, a_n)

AnA_n is what a spectrum analyser shows as the height of each line, and it doesn't change if you shift the signal in time. Only the phases φn\varphi_n change.

Complex exponential form​

Using Euler's formula, eiθ=cos⁡θ+isin⁡θe^{i\theta} = \cos\theta + i\sin\theta, the sines and cosines fold into one sum over positive and negative nn. This is the complex (or exponential) Fourier series:

f(t)=∑n=−∞∞cn einω0t,cn=1T∫0Tf(t) e−inω0t dtf(t) = \sum_{n=-\infty}^{\infty} c_n\, e^{i n \omega_0 t}, \qquad c_n = \frac{1}{T} \int_{0}^{T} f(t)\, e^{-i n \omega_0 t}\, dt

The two sets of coefficients convert directly:

Complex formTrigonometric form
c0c_0a0/2a_0/2 (the average)
cnc_n, for n>0n > 0(an−i bn)/2(a_n - i\, b_n)/2
c−nc_{-n}(an+i bn)/2(a_n + i\, b_n)/2, the complex conjugate of cnc_n for a real signal
∣cn∣\lvert c_n \rvertAn/2A_n / 2: half the amplitude sits at +n+n, half at −n-n

The complex form is shorter to write and to manipulate, and it is the form the Fourier transform and the DFT grow out of. The trigonometric form is easier to picture.

Worked example: the Fourier series of a square wave​

Take a square wave that is +1+1 for the first half of each period and −1-1 for the second half.

  1. Use the symmetry. The wave is an odd function, f(−t)=−f(t)f(-t) = -f(t), so every cosine coefficient is zero: a0=an=0a_0 = a_n = 0. Only the bnb_n are left.
  2. Integrate each half of the period. With ω0T=2π\omega_0 T = 2\pi: bn=2T[∫0T/2sin⁡(nω0t) dt−∫T/2Tsin⁡(nω0t) dt]=2 (1−cos⁡nπ)nπb_n = \frac{2}{T}\left[ \int_0^{T/2} \sin(n\omega_0 t)\, dt - \int_{T/2}^{T} \sin(n\omega_0 t)\, dt \right] = \frac{2\,(1 - \cos n\pi)}{n\pi}
  3. Read off the pattern. cos⁡nπ\cos n\pi is −1-1 for odd nn and +1+1 for even nn. So bn=4/(nπ)b_n = 4/(n\pi) for odd nn, and bn=0b_n = 0 for even nn.

The square wave's Fourier series is therefore:

f(t)=4π(sin⁡ω0t+13sin⁡3ω0t+15sin⁡5ω0t+17sin⁡7ω0t+⋯ )f(t) = \frac{4}{\pi} \left( \sin \omega_0 t + \frac{1}{3} \sin 3\omega_0 t + \frac{1}{5} \sin 5\omega_0 t + \frac{1}{7} \sin 7\omega_0 t + \cdots \right)
Harmonic nnbn=4/(nπ)b_n = 4/(n\pi)Share of the wave's power, up to and including nn
11.273281.1%
30.424490.1%
50.254693.3%
70.181995.0%
up to 9999.6%

The power column uses Parseval's theorem: the mean square of the signal (here 1) equals a02/4+12∑(an2+bn2)a_0^2/4 + \tfrac{1}{2}\sum (a_n^2 + b_n^2). So the fundamental alone carries 8/π2≈81%8/\pi^2 \approx 81\% of a square wave's power, and the last few per cent are spread over a long tail of harmonics. That tail is what makes the edges sharp.

At t=T/4t = T/4 the square wave is 1 and every sine is ±1\pm 1, so the series gives 1=4π(1−13+15−⋯ )1 = \tfrac{4}{\pi}(1 - \tfrac{1}{3} + \tfrac{1}{5} - \cdots). That is the Leibniz series for π/4\pi/4.

Fourier series examples: square, sawtooth, triangle and pulse waves​

All four waves below swing between −1-1 and +1+1 (the pulse train between 0 and 1) and repeat every TT. You can draw each of them, with any number of harmonics, in the live grapher.

Waveform (one period)Fourier seriesHarmonics presentAmplitudes fall asPower in the fundamental
Square, +1+1 then −1-14π∑n oddsin⁡nω0tn\dfrac{4}{\pi} \displaystyle\sum_{n \text{ odd}} \frac{\sin n\omega_0 t}{n}Odd only1/n1/n81.1%
Sawtooth, rising from −1-1 to +1+1, centred on t=0t = 02π∑n=1∞(−1)n+1sin⁡nω0tn\dfrac{2}{\pi} \displaystyle\sum_{n=1}^{\infty} (-1)^{n+1} \frac{\sin n\omega_0 t}{n}All1/n1/n60.8%
Triangle, peak +1+1 at t=0t = 08π2∑n oddcos⁡nω0tn2\dfrac{8}{\pi^2} \displaystyle\sum_{n \text{ odd}} \frac{\cos n\omega_0 t}{n^2}Odd only1/n21/n^298.6%
Pulse train, 1 for a fraction DD of each period (the duty cycle), centred on t=0t = 0D+∑n=1∞2sin⁡(nπD)nπcos⁡nω0tD + \displaystyle\sum_{n=1}^{\infty} \frac{2 \sin(n\pi D)}{n\pi} \cos n\omega_0 tAll, except where nDnD is a whole number1/n1/n (under a sinc-shaped envelope)depends on DD

The smoother a waveform, the faster its coefficients fall, because the faster a waveform changes, the more high harmonics it needs:

  • The square, sawtooth and pulse waves jump, so their coefficients fall only as 1/n1/n. Even harmonic 99 still has about 1% of the fundamental's amplitude.
  • The triangle is continuous but has corners (its slope jumps), so its coefficients fall as 1/n21/n^2. Harmonic 9 is already down to about 1%.
  • In general, if a signal and its first k−1k-1 derivatives are continuous and the kkth derivative jumps, the coefficients fall as 1/nk+11/n^{k+1}. A signal with no corners at all, such as a rounded pulse, needs very few harmonics.

So a square-wave clock signal radiates interference at high frequencies, and a triangle wave sounds much mellower than a square wave at the same pitch.

Pulse trains show one more effect. With D=25%D = 25\%, the coefficient sin⁡(nπD)\sin(n\pi D) is zero at n=4,8,12…n = 4, 8, 12 \ldots, so every fourth harmonic is missing. A narrower pulse spreads its power over more harmonics, and as DD shrinks towards zero the line spectrum fills in towards the continuous sinc shape of a single pulse's Fourier transform.

Even and odd symmetry shortcuts​

Spotting symmetry before you integrate halves the work, and often tells you that whole groups of coefficients are zero.

SymmetryTestCoefficients that are zeroWhat's left
Evenf(−t)=f(t)f(-t) = f(t): a mirror image about t=0t = 0All bnb_nA Fourier cosine series, with an=4T∫0T/2f(t)cos⁡(nω0t) dta_n = \frac{4}{T}\int_0^{T/2} f(t)\cos(n\omega_0 t)\,dt
Oddf(−t)=−f(t)f(-t) = -f(t): rotate by half a turn about the origina0a_0 and all ana_nA Fourier sine series, with bn=4T∫0T/2f(t)sin⁡(nω0t) dtb_n = \frac{4}{T}\int_0^{T/2} f(t)\sin(n\omega_0 t)\,dt
Half-wavef(t+T/2)=−f(t)f(t + T/2) = -f(t): the second half is the first half upside downAll even harmonics, including a0a_0Odd harmonics only

The square wave is odd and half-wave symmetric, so only odd sine terms survive. The triangle above is even and half-wave symmetric, so only odd cosine terms survive. The sawtooth is odd but not half-wave symmetric, so it has every sine harmonic.

Two more shortcuts: adding a constant to a signal changes only a0a_0, and shifting it in time changes only the phases, never the amplitudes AnA_n. So a square wave that runs from 0 to 1 has the same harmonics as the one above, at half the size, plus an average of 1/21/2.

Convergence and the Gibbs phenomenon​

If a periodic signal has a finite number of jumps, peaks and troughs in each period, and the area under its absolute value over a period is finite (the Dirichlet conditions), then its Fourier series converges:

  • to f(t)f(t) wherever the signal is continuous;
  • to the midpoint of the jump wherever it jumps. At the square wave's edges, every partial sum passes through 0.

Even without those conditions, the series converges in the mean-square sense for any signal with finite power: the RMS error between SN(t)S_N(t) and f(t)f(t) goes to zero as NN grows. For the square wave it is 0.44 with one harmonic, 0.16 with harmonics up to 15 and 0.06 up to 99. For the triangle it is 0.0036 already at 15.

The Gibbs phenomenon at a jump​

Near a jump, the partial sum doesn't settle. It overshoots and rings, and the overshoot doesn't shrink as you add terms. This is the Gibbs phenomenon. The overshoot stays at about 8.95% of the jump on each side; adding harmonics only squeezes the ripple into a narrower region next to the jump.

A close-up of a square wave's jump from −1 to +1 at t = 0. Partial sums with N = 15 and N = 61 harmonics both peak at about 1.18, an overshoot of 9% of the jump of 2; the N = 61 ripple sits closer to the jump. A partial sum with N = 61 and Lanczos sigma smoothing peaks at about 1.02, with a slightly slower rise

The exact limit is 1π∫0πsin⁡xx dx−12≈0.0895\frac{1}{\pi}\int_0^{\pi} \frac{\sin x}{x}\,dx - \frac{1}{2} \approx 0.0895 of the jump. For a square wave from −1-1 to +1+1, the partial sums peak near 1.1791.179. Henry Wilbraham described the overshoot in 1848; it is named after J. Willard Gibbs, who wrote about it in 1899.

Reducing the Gibbs overshoot with sigma factors​

The ringing comes from cutting the series off abruptly at harmonic NN. Tapering the coefficients instead, by multiplying harmonic nn by a Lanczos sigma factor σn=sinc⁡(n/(N+1))\sigma_n = \operatorname{sinc}\big(n/(N+1)\big), cuts the overshoot from about 9% to about 1.2% of the jump, but it softens the edge and slightly raises the RMS error (about 0.078 instead of 0.064 for the square wave at N=100N = 100). This is the same trade-off a window function makes in spectrum analysis, and Gibbs ringing is the same effect you see as ringing from a sharp low-pass filter.

Fourier series vs Fourier transform vs DFT​

All three describe a signal by its frequencies. Which one applies depends on whether the signal repeats and whether it is sampled.

Your signalToolIts spectrumTypical use
Continuous and periodic (repeats every TT)Fourier seriesSeparate lines at f0,2f0,3f0…f_0, 2f_0, 3f_0 \ldotsAnalysing or building a repeating waveform on paper: square waves, harmonics, AC power, musical tones
Continuous and not periodic (a pulse, a transient, a chirp)Fourier transformA continuous curve over all frequenciesTheory of filters, modulation and signals that start and stop
Sampled, a finite block of MM samplesDiscrete Fourier transform (DFT), computed with an FFTMM lines, fs/Mf_s/M apartAnything measured: audio, vibration, sensor data
Sampled and periodic (repeats every MM samples)Discrete-time Fourier series (DTFS)MM lines, exactlyThe same sums as the DFT, scaled by 1/M1/M

The rows are closely linked. The Fourier transform is the limit of a Fourier series as the period grows to infinity: the lines get closer together until they merge into a curve. The DFT is a Fourier series of the samples, because it treats the block as one period of a signal that repeats forever. That is why the DFT can find a waveform's Fourier coefficients, as the next section shows.

How to find Fourier series coefficients from sampled data​

In practice you rarely have a formula for f(t)f(t). You have samples. To estimate the coefficients:

  1. Sample exactly one period (or a whole number of periods) at MM evenly spaced points, x[k]=f(kT/M)x[k] = f(kT/M) for k=0…M−1k = 0 \ldots M-1. A sample that lands on a jump should take the midpoint value.
  2. Take the DFT, X[n]=∑k=0M−1x[k] e−2πink/MX[n] = \sum_{k=0}^{M-1} x[k]\, e^{-2\pi i n k / M}, usually with an FFT.
  3. Scale by 1/M1/M: cn≈X[n]/Mc_n \approx X[n]/M. In trigonometric form, an≈2MRe⁡X[n]a_n \approx \tfrac{2}{M}\operatorname{Re} X[n] and bn≈−2MIm⁡X[n]b_n \approx -\tfrac{2}{M}\operatorname{Im} X[n].

This is the coefficient formula with the integral replaced by a sum over the samples. The estimate is good for harmonics well below M/2M/2; higher harmonics of the signal fold back onto the lower ones (aliasing). We sampled one period of the square wave and compared the estimates with the exact 4/(nπ)4/(n\pi):

Harmonic nnExact bnb_nFrom M=64M = 64 samplesFrom M=1,024M = 1{,}024 samples
11.273241.272221.27324
30.424410.421340.42440
50.254650.249510.25463
70.181890.174680.18186

The estimates get worse as nn rises towards M/2M/2, and better with more samples per period. In JavaScript, a direct version for a handful of harmonics is only a few lines (use an FFT when you need many):

// Fourier series coefficients a[n] and b[n], n = 0 ... nMax, from M samples of exactly one period
function seriesFromSamples(samples, nMax) {
const M = samples.length;
const a = [];
const b = [];
for (let n = 0; n <= nMax; n++) {
let sumCos = 0;
let sumSin = 0;
for (let k = 0; k < M; k++) {
const angle = (2 * Math.PI * n * k) / M;
sumCos += samples[k] * Math.cos(angle);
sumSin += samples[k] * Math.sin(angle);
}
a.push((2 * sumCos) / M); // a[0] / 2 is the average
b.push((2 * sumSin) / M);
}
return { a, b };
}

If the block isn't a whole number of periods, the DFT sees a jump where the end of the block meets the start. The harmonics then spread into neighbouring bins (spectral leakage), and the bins no longer line up with the harmonics. Trim the block to whole periods, or resample it so they fit; a window function reduces the leakage but doesn't put the bins back on the harmonics.

Common Fourier series mistakes​

Most Fourier series mistakes are slips in the coefficient formulas, or misreadings of what a partial sum shows.

  • Forgetting the a0/2a_0/2. If you compute a0a_0 with the same 2/T2/T formula as the other ana_n, the constant term is a0/2a_0/2, not a0a_0. Some books define a0a_0 as the average itself, with 1/T1/T; check which convention a table uses.
  • Integrating over less (or more) than one full period. The orthogonality that makes the formulas work holds only over whole periods. With sampled data, a block that isn't a whole number of periods causes leakage.
  • Confusing harmonic number with frequency. Harmonic nn is at nf0n f_0 hertz. Harmonic 5 of a 60 Hz waveform is at 300 Hz, not 5 Hz.
  • Mixing one-sided and two-sided amplitudes. The amplitude of harmonic nn is An=2∣cn∣A_n = 2\lvert c_n \rvert. Reading ∣cn∣\lvert c_n \rvert as the amplitude halves every harmonic.
  • Applying a Fourier series to a signal that doesn't repeat. The series is periodic, so it repeats your interval forever, jump at the join included. For one-off signals, use the Fourier transform.
  • Sampling too slowly for the harmonics you want. You need more than 2n2n samples per period to estimate harmonic nn, and many more if the signal jumps, because its harmonics never stop.

How to graph a Fourier series in JavaScript, React or Angular​

Each time you move a control, the grapher below re-adds up to 100 harmonics at 5,001 points across two periods, using the plain JavaScript functions in the code, and redraws the wave and its spectrum. Pick a waveform (square, sawtooth, triangle or a pulse train with a duty cycle), drag the harmonics slider from 1 to 100, show the harmonics being added, and turn on Lanczos σ smoothing to see the Gibbs overshoot drop. The line under the controls gives the overshoot and the RMS error. Zoom in on a jump to see the Gibbs ripples up close; hover to read values, drag to pan and double-click to reset.

Here is the code for this example. The JavaScript tab includes the coefficient and partial-sum functions; the React and Angular tabs reuse them.

// Fourier series grapher: a periodic waveform, its partial sum with N harmonics and its harmonic spectrum,
// in JavaScript with SciChart.js. The Fourier series functions below are plain JavaScript with no dependencies.

// Every waveform here has period T = 1 s, so the fundamental is f0 = 1 Hz and harmonic n is n Hz.
// The series is f(t) = a0/2 + sum over n of (a[n] cos(2 pi n t) + b[n] sin(2 pi n t)).

// Fourier coefficients a[n] and b[n] for n = 0 ... nMax, worked out from the coefficient integrals.
// duty is the fraction of each period a pulse train is high (0 to 1).
function fourierCoefficients(waveform, nMax, duty) {
const a = new Float64Array(nMax + 1);
const b = new Float64Array(nMax + 1);
for (let n = 1; n <= nMax; n++) {
const odd = n % 2 === 1;
if (waveform === "square") {
b[n] = odd ? 4 / (Math.PI * n) : 0; // odd function: sines only; odd harmonics only; 1/n
} else if (waveform === "sawtooth") {
b[n] = ((odd ? 1 : -1) * 2) / (Math.PI * n); // odd function: sines only; every harmonic; 1/n
} else if (waveform === "triangle") {
a[n] = odd ? 8 / (Math.PI * Math.PI * n * n) : 0; // even function: cosines only; odd harmonics; 1/n^2
} else {
// pulse train centred on t = 0: zero when n * duty is a whole number (rounding would leave ~1e-16)
const s = Math.sin(Math.PI * n * duty);
a[n] = Math.abs(s) < 1e-9 ? 0 : (2 * s) / (Math.PI * n);
}
}
a[0] = waveform === "pulse" ? 2 * duty : 0; // a0/2 is the average value
return { a, b };
}

// The waveform itself. At a jump it returns the midpoint, which is the value the series converges to.
function targetWaveform(waveform, t, duty) {
const x = t - Math.round(t); // position within the period, from -0.5 to 0.5
if (waveform === "square") {
if (x === 0 || Math.abs(x) === 0.5) return 0;
return x > 0 ? 1 : -1;
}
if (waveform === "sawtooth") return Math.abs(x) === 0.5 ? 0 : 2 * x;
if (waveform === "triangle") return 1 - 4 * Math.abs(x);
const distance = Math.abs(x);
if (Math.abs(distance - duty / 2) < 1e-12) return 0.5;
return distance < duty / 2 ? 1 : 0;
}

// Lanczos sigma factor for harmonic n of an N-harmonic sum: sinc(n / (N + 1)).
// Multiplying each term by it smooths the ripple near a jump (Gibbs overshoot) at the cost of a softer edge.
function lanczosSigma(n, N) {
const x = (Math.PI * n) / (N + 1);
return Math.sin(x) / x;
}

// One term of the series, harmonic n at time t (with its sigma factor, if smoothing is on)
function harmonicTerm(coefficients, n, t, weight) {
const angle = 2 * Math.PI * n * t;
return weight * (coefficients.a[n] * Math.cos(angle) + coefficients.b[n] * Math.sin(angle));
}

// The partial sum S_N(t): the average plus harmonics 1 to N
function partialSum(coefficients, N, t, smooth) {
let sum = coefficients.a[0] / 2;
for (let n = 1; n <= N; n++) {
if (coefficients.a[n] === 0 && coefficients.b[n] === 0) continue;
sum += harmonicTerm(coefficients, n, t, smooth ? lanczosSigma(n, N) : 1);
}
return sum;
}

// The 1/n or 1/n^2 curve each waveform's harmonic amplitudes follow
const ENVELOPES = {
square: { label: "4/(πn)", at: (n) => 4 / (Math.PI * n) },
sawtooth: { label: "2/(πn)", at: (n) => 2 / (Math.PI * n) },
triangle: { label: "8/(π²n²)", at: (n) => 8 / (Math.PI * Math.PI * n * n) },
pulse: { label: "2/(πn)", at: (n) => 2 / (Math.PI * n) }
};

const MAX_HARMONIC = 100;
const POINTS_PER_PERIOD = 2500;
const MAX_TERMS_DRAWN = 8; // individual harmonics drawn when "Show harmonics" is on

async function createFourierSeriesCharts(timeDiv, spectrumDiv) {
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EXyDirection,
XyDataSeries,
FastLineRenderableSeries,
FastImpulseRenderableSeries,
EllipsePointMarker,
SciChartJsNavyTheme,
LegendModifier,
ELegendOrientation,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// Top chart: the target waveform, the partial sum and (optionally) the harmonics being added up
const time = await SciChartSurface.create(timeDiv, { theme: new SciChartJsNavyTheme() });
time.sciChartSurface.xAxes.add(
new NumericAxis(time.wasmContext, { axisTitle: "Time (s), two periods", labelPrecision: 1 })
);
const valueAxis = new NumericAxis(time.wasmContext, { axisTitle: "Value", labelPrecision: 1 });
time.sciChartSurface.yAxes.add(valueAxis);
const termsData = new XyDataSeries(time.wasmContext, { dataSeriesName: `Harmonics (first ${MAX_TERMS_DRAWN} terms)`, isSorted: false, containsNaN: true });
const targetData = new XyDataSeries(time.wasmContext, { dataSeriesName: "Target waveform", dataIsSortedInX: true });
const sumData = new XyDataSeries(time.wasmContext, { dataSeriesName: "Partial sum S_N(t)", dataIsSortedInX: true });
const termsLine = new FastLineRenderableSeries(time.wasmContext, { dataSeries: termsData, stroke: "#F4842099", strokeThickness: 1 });
time.sciChartSurface.renderableSeries.add(
termsLine,
new FastLineRenderableSeries(time.wasmContext, { dataSeries: targetData, stroke: "#F5E663", strokeThickness: 1.5 }),
new FastLineRenderableSeries(time.wasmContext, { dataSeries: sumData, stroke: "#50C7E0", strokeThickness: 2.5 })
);
time.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true, orientation: ELegendOrientation.Horizontal }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier()
);

// Bottom chart: the amplitude of each harmonic, the ones in the sum and the ones left out
const spectrum = await SciChartSurface.create(spectrumDiv, { theme: new SciChartJsNavyTheme() });
const harmonicAxis = new NumericAxis(spectrum.wasmContext, { axisTitle: "Harmonic number n (frequency = n × f0)", labelPrecision: 0 });
spectrum.sciChartSurface.xAxes.add(harmonicAxis);
spectrum.sciChartSurface.yAxes.add(
new NumericAxis(spectrum.wasmContext, {
axisTitle: "Amplitude",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.45), // room at the top for the legend
labelPrecision: 2
})
);
const includedData = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "In the sum (n ≤ N)" });
const omittedData = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "Left out (n > N)" });
const envelopeData = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "Envelope (1/n or 1/n²)", dataIsSortedInX: true });
spectrum.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(spectrum.wasmContext, {
dataSeries: envelopeData,
stroke: "#F5E663",
strokeThickness: 1.5,
strokeDashArray: [6, 4]
}),
new FastImpulseRenderableSeries(spectrum.wasmContext, {
dataSeries: omittedData,
stroke: "#A9B6CCAA",
fill: "#A9B6CCAA",
strokeThickness: 2,
size: 6,
pointMarker: new EllipsePointMarker(spectrum.wasmContext)
}),
new FastImpulseRenderableSeries(spectrum.wasmContext, {
dataSeries: includedData,
stroke: "#F48420",
fill: "#F48420",
strokeThickness: 3,
size: 8,
pointMarker: new EllipsePointMarker(spectrum.wasmContext)
})
);
spectrum.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true, orientation: ELegendOrientation.Horizontal }),
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (seriesInfos) =>
seriesInfos
.filter((info) => info.isHit && !info.seriesName.startsWith("Envelope"))
.map((info) => `n = ${info.xValue} (${info.xValue} Hz): amplitude ${info.yValue.toFixed(4)}`)
}),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier()
);

// Recompute everything from the settings: { waveform, duty, N, showTerms, smooth }.
// Returns the number of non-zero terms, the envelope formula, the Gibbs overshoot (as a % of the jump) and the RMS error of the partial sum.
const update = (settings) => {
const { waveform, duty, N, showTerms, smooth } = settings;
const coefficients = fourierCoefficients(waveform, MAX_HARMONIC, duty);

// Time domain: t from -1 s to 1 s
const xs = [];
const target = [];
const sum = [];
for (let i = -POINTS_PER_PERIOD; i <= POINTS_PER_PERIOD; i++) {
const t = i / POINTS_PER_PERIOD;
xs.push(t);
target.push(targetWaveform(waveform, t, duty));
sum.push(partialSum(coefficients, N, t, smooth));
}
targetData.clear();
targetData.appendRange(xs, target);
sumData.clear();
sumData.appendRange(xs, sum);
valueAxis.visibleRange = waveform === "pulse" ? new NumberRange(-0.6, 1.9) : new NumberRange(-1.5, 2.1); // room at the top for the legend

// The individual harmonics (the first few non-zero ones), separated by NaN gaps in one series
termsData.clear();
let drawn = 0;
for (let n = 1; n <= N && showTerms && drawn < MAX_TERMS_DRAWN; n++) {
if (coefficients.a[n] === 0 && coefficients.b[n] === 0) continue;
const weight = smooth ? lanczosSigma(n, N) : 1;
termsData.appendRange(xs, xs.map((t) => harmonicTerm(coefficients, n, t, weight)));
termsData.append(NaN, NaN);
drawn++;
}
termsLine.isVisible = showTerms;

// Harmonic spectrum: amplitude A_n = sqrt(a_n^2 + b_n^2), and |a0/2| at n = 0
const limit = Math.min(MAX_HARMONIC, Math.max(20, N + 10));
const amplitude = (n) => (n === 0 ? Math.abs(coefficients.a[0] / 2) : Math.hypot(coefficients.a[n], coefficients.b[n]));
const inX = [];
const inY = [];
const outX = [];
const outY = [];
for (let n = 0; n <= limit; n++) {
const value = amplitude(n) * (smooth && n > 0 && n <= N ? lanczosSigma(n, N) : 1);
if (value < 1e-12) continue; // skip the harmonics that are exactly zero
if (n <= N) {
inX.push(n);
inY.push(value);
} else {
outX.push(n);
outY.push(value);
}
}
includedData.clear();
includedData.appendRange(inX, inY);
omittedData.clear();
omittedData.appendRange(outX, outY);
const envelope = ENVELOPES[waveform];
const envX = [];
for (let x = 1; x <= limit; x += 0.25) envX.push(x);
envelopeData.clear();
envelopeData.appendRange(envX, envX.map(envelope.at));
harmonicAxis.visibleRange = new NumberRange(-0.5, limit + 0.5);

// Gibbs overshoot: how far the partial sum rises above the waveform's top, as a % of the jump.
// RMS error: the root-mean-square gap between the partial sum and the waveform over one period.
let top = -Infinity;
let bottom = Infinity;
let peak = -Infinity;
let squaredError = 0;
let count = 0;
for (let i = 0; i < xs.length; i++) {
top = Math.max(top, target[i]);
bottom = Math.min(bottom, target[i]);
peak = Math.max(peak, sum[i]);
if (xs[i] >= 0 && xs[i] < 1) {
squaredError += (sum[i] - target[i]) ** 2;
count++;
}
}
let nonZeroTerms = 0;
for (let n = 1; n <= N; n++) if (coefficients.a[n] !== 0 || coefficients.b[n] !== 0) nonZeroTerms++;
return {
nonZeroTerms,
envelopeLabel: envelope.label,
overshootPercent: (100 * (peak - top)) / (top - bottom),
rmsError: Math.sqrt(squaredError / count),
hasJump: waveform !== "triangle"
};
};
return { update };
}

Key points:

  • The partial sum is an XyDataSeries of times and values, drawn by a FastLineRenderableSeries. A few thousand points per period are enough to show the Gibbs ripple even at 100 harmonics.
  • The harmonic spectrum is a FastImpulseRenderableSeries (a stem chart) with an EllipsePointMarker on each stem. A second impulse series in grey shows the harmonics the sum leaves out.
  • The individual harmonics share one XyDataSeries, separated by NaN values that the line series draws as gaps, so they need only one legend entry.
  • To update the chart live, keep the data series and call clear() then appendRange() with the new values, as the example's update() function does. SciChart.js redraws on the next frame.

See it in the demo app: JavaScript audio spectrum analyzer chart · React audio spectrum analyzer chart · Angular audio spectrum analyzer chart. It analyses live audio from your microphone, where you can see the harmonics of your own voice or an instrument.

Go deeper: SciChart.js impulse (stem) series documentation, the line series documentation, and the FFT guide for measuring the spectrum of real signals.

Frequently asked questions​

What is the Fourier series formula?​

For a signal f(t)f(t) that repeats every TT seconds, with fundamental angular frequency ω0=2π/T\omega_0 = 2\pi/T, the Fourier series is f(t)=a0/2+∑n=1∞(ancos⁡nω0t+bnsin⁡nω0t)f(t) = a_0/2 + \sum_{n=1}^{\infty} (a_n \cos n\omega_0 t + b_n \sin n\omega_0 t). The coefficients are an=2T∫0Tf(t)cos⁡(nω0t) dta_n = \frac{2}{T}\int_0^T f(t)\cos(n\omega_0 t)\,dt and bn=2T∫0Tf(t)sin⁡(nω0t) dtb_n = \frac{2}{T}\int_0^T f(t)\sin(n\omega_0 t)\,dt. The term a0/2a_0/2 is the signal's average value.

What is the Fourier series of a square wave?​

A square wave that is +1 for the first half of each period and −1 for the second half has the Fourier series 4π(sin⁡ω0t+13sin⁡3ω0t+15sin⁡5ω0t+⋯ )\frac{4}{\pi}(\sin \omega_0 t + \frac{1}{3}\sin 3\omega_0 t + \frac{1}{5}\sin 5\omega_0 t + \cdots). It contains only odd harmonics, and the amplitude of harmonic nn is 4/(nπ)4/(n\pi), so it falls as 1/n1/n. The fundamental alone carries about 81% of the wave's power.

What is the difference between a Fourier series and a Fourier transform?​

A Fourier series describes a periodic signal as a sum of sine waves at whole-number multiples of its repeat frequency, so its spectrum is a set of separate lines. A Fourier transform works on signals that don't repeat and gives a continuous spectrum. For sampled data, the discrete Fourier transform (DFT) plays both roles: it treats a block of samples as one period of a repeating signal.

What is the Gibbs phenomenon?​

The Gibbs phenomenon is the overshoot a Fourier series makes next to a jump in the signal. However many harmonics you add, the partial sum overshoots by about 9% of the jump on each side; more harmonics only squeeze the ripple closer to the jump. Smoothing the coefficients, for example with Lanczos sigma factors, reduces the overshoot to about 1.2%, at the cost of a less steep edge.

How do I find Fourier series coefficients from measured data?​

Sample exactly one period (or a whole number of periods) of the signal at MM evenly spaced points and take its discrete Fourier transform. Bin nn of the DFT divided by MM approximates the complex coefficient cnc_n, so ana_n is 2/M2/M times the real part of X[n]X[n] and bnb_n is minus 2/M2/M times its imaginary part. The approximation is good while nn is well below M/2M/2 and the sample rate is high enough to avoid aliasing.

How do I plot a Fourier series in JavaScript?​

Compute the coefficients ana_n and bnb_n, evaluate the partial sum a0/2+∑n=1N(ancos⁡nω0t+bnsin⁡nω0t)a_0/2 + \sum_{n=1}^{N} (a_n \cos n\omega_0 t + b_n \sin n\omega_0 t) at a few thousand time points, and plot the result as a line. With SciChart.js, put the times and values in an XyDataSeries and draw them with a FastLineRenderableSeries; draw the harmonic amplitudes with a FastImpulseRenderableSeries. In React or Angular, create the same charts inside scichart-react's SciChartReact or scichart-angular's ScichartAngularComponent.

Sources​