Fourier Series
What is a Fourier series?
A Fourier series is a way of writing a periodic signal, one that repeats every seconds, as a sum of sine and cosine waves. The waves are the harmonics: the fundamental frequency and its whole-number multiples Each harmonic has its own amplitude, given by the signal's Fourier coefficients.

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.
- Any practical periodic signal is a sum of harmonics at , plus a constant (its average).
- The coefficients and 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 . 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: .
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.
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 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 with period , write the fundamental angular frequency as . The trigonometric Fourier series is:
and its Fourier series coefficients are integrals over any one period:
- is the average value of the signal over a period (the DC level). Writing it as lets the same formula work for .
- measures the cosine part of harmonic , and the sine part.
- Harmonic has frequency hertz. For a 50 Hz waveform, harmonic 3 is at 150 Hz.
- Stopping the sum at gives the partial sum , 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:
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 change.
Complex exponential form
Using Euler's formula, , the sines and cosines fold into one sum over positive and negative . This is the complex (or exponential) Fourier series:
The two sets of coefficients convert directly:
| Complex form | Trigonometric form |
|---|---|
| (the average) | |
| , for | |
| , the complex conjugate of for a real signal | |
| : half the amplitude sits at , half at |
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 for the first half of each period and for the second half.
- Use the symmetry. The wave is an odd function, , so every cosine coefficient is zero: . Only the are left.
- Integrate each half of the period. With :
- Read off the pattern. is for odd and for even . So for odd , and for even .
The square wave's Fourier series is therefore:
| Harmonic | Share of the wave's power, up to and including | |
|---|---|---|
| 1 | 1.2732 | 81.1% |
| 3 | 0.4244 | 90.1% |
| 5 | 0.2546 | 93.3% |
| 7 | 0.1819 | 95.0% |
| up to 99 | 99.6% |
The power column uses Parseval's theorem: the mean square of the signal (here 1) equals . So the fundamental alone carries 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 the square wave is 1 and every sine is , so the series gives . That is the Leibniz series for .
Fourier series examples: square, sawtooth, triangle and pulse waves
All four waves below swing between and (the pulse train between 0 and 1) and repeat every . You can draw each of them, with any number of harmonics, in the live grapher.
| Waveform (one period) | Fourier series | Harmonics present | Amplitudes fall as | Power in the fundamental |
|---|---|---|---|---|
| Square, then | Odd only | 81.1% | ||
| Sawtooth, rising from to , centred on | All | 60.8% | ||
| Triangle, peak at | Odd only | 98.6% | ||
| Pulse train, 1 for a fraction of each period (the duty cycle), centred on | All, except where is a whole number | (under a sinc-shaped envelope) | depends on |
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 . 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 . Harmonic 9 is already down to about 1%.
- In general, if a signal and its first derivatives are continuous and the th derivative jumps, the coefficients fall as . 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 , the coefficient is zero at , so every fourth harmonic is missing. A narrower pulse spreads its power over more harmonics, and as 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.
| Symmetry | Test | Coefficients that are zero | What's left |
|---|---|---|---|
| Even | : a mirror image about | All | A Fourier cosine series, with |
| Odd | : rotate by half a turn about the origin | and all | A Fourier sine series, with |
| Half-wave | : the second half is the first half upside down | All even harmonics, including | Odd 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 , and shifting it in time changes only the phases, never the amplitudes . 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 .
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 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 and goes to zero as 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.
The exact limit is of the jump. For a square wave from to , the partial sums peak near . 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 . Tapering the coefficients instead, by multiplying harmonic by a Lanczos sigma factor , cuts the overshoot from about 9% to about 1.2% of the jump, but it softens the edge and slightly raises the RMS error (0.075 instead of 0.060 for the square wave at ). 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 signal | Tool | Its spectrum | Typical use |
|---|---|---|---|
| Continuous and periodic (repeats every ) | Fourier series | Separate lines at | Analysing 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 transform | A continuous curve over all frequencies | Theory of filters, modulation and signals that start and stop |
| Sampled, a finite block of samples | Discrete Fourier transform (DFT), computed with an FFT | lines, apart | Anything measured: audio, vibration, sensor data |
| Sampled and periodic (repeats every samples) | Discrete-time Fourier series (DTFS) | lines, exactly | The same sums as the DFT, scaled by |
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 . You have samples. To estimate the coefficients:
- Sample exactly one period (or a whole number of periods) at evenly spaced points, for . A sample that lands on a jump should take the midpoint value.
- Take the DFT, , usually with an FFT.
- Scale by : . In trigonometric form, and .
This is the coefficient formula with the integral replaced by a sum over the samples. The estimate is good for harmonics well below ; 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 :
| Harmonic | Exact | From samples | From samples |
|---|---|---|---|
| 1 | 1.27324 | 1.27222 | 1.27324 |
| 3 | 0.42441 | 0.42134 | 0.42440 |
| 5 | 0.25465 | 0.24951 | 0.25463 |
| 7 | 0.18189 | 0.17468 | 0.18186 |
The estimates get worse as rises towards , 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
- Forgetting the . If you compute with the same formula as the other , the constant term is , not . Some books define as the average itself, with ; 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 is at 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 is . Reading 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 samples per period to estimate harmonic , and many more if the signal jumps, because its harmonics never stop.
How to graph a Fourier series in JavaScript, React or Angular
SciChart.js draws signals and spectra with WebGL and WebGPU, fast enough to redraw thousands of points every time a control moves. The grapher below computes each partial sum in your browser with the plain JavaScript functions in the code. 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. Hover to read values, scroll to zoom, 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.
- JavaScript
- React
- Angular
// 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 };
}
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// partialSum: copy it from the JavaScript tab
import { partialSum } from "./fourierSeries";
const N = 15; // highest harmonic in the sum
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Value" }));
// Your coefficients: { a, b } arrays indexed by harmonic number, period 1 s
const coefficients = getYourCoefficients();
const times = Array.from({ length: 2001 }, (_, i) => -1 + i / 1000);
const values = times.map((t) => partialSum(coefficients, N, t, false));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: times, yValues: values, dataIsSortedInX: true }),
stroke: "#50C7E0",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const FourierSeriesChart = () => <SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />;
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// partialSum: copy it from the JavaScript tab
import { partialSum } from "./fourierSeries";
const N = 15; // highest harmonic in the sum
@Component({
selector: "app-fourier-series-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class FourierSeriesChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Value" }));
// Your coefficients: { a, b } arrays indexed by harmonic number, period 1 s
const coefficients = getYourCoefficients();
const times = Array.from({ length: 2001 }, (_, i) => -1 + i / 1000);
const values = times.map((t) => partialSum(coefficients, N, t, false));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: times, yValues: values, dataIsSortedInX: true }),
stroke: "#50C7E0",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
- The partial sum is an
XyDataSeriesof times and values, drawn by aFastLineRenderableSeries. 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 anEllipsePointMarkeron each stem. A second impulse series in grey shows the harmonics the sum leaves out. - The individual harmonics share one
XyDataSeries, separated byNaNvalues 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()thenappendRange()with the new values, as the example'supdate()function does. SciChart.js redraws on the next frame.
See it in the demo app: JavaScript real-time spectrum chart · React real-time spectrum chart · Angular real-time spectrum 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) chart 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 that repeats every seconds, with fundamental angular frequency , the Fourier series is . The coefficients are and . The term 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 . It contains only odd harmonics, and the amplitude of harmonic is , so it falls as . 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 around 1%, 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 evenly spaced points and take its discrete Fourier transform. Bin of the DFT divided by approximates the complex coefficient , so is times the real part of and is minus times its imaginary part. The approximation is good while is well below and the sample rate is high enough to avoid aliasing.
How do I plot a Fourier series in JavaScript?
Compute the coefficients and , evaluate the partial sum 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. The same charts work in React with scichart-react and in Angular with scichart-angular.
Sources
- Fourier, J. (1822), Théorie analytique de la chaleur. Paris: Firmin Didot. The origin of Fourier series (English translation, 1878, at the Internet Archive).
- Oppenheim, A. V. and Willsky, A. S. with Nawab, S. H. (1997), Signals and Systems, 2nd edition, Prentice Hall, chapter 3, Fourier Series Representation of Periodic Signals. Trigonometric and complex forms, convergence and the discrete-time Fourier series.
- Smith, S. W., The Scientist and Engineer's Guide to Digital Signal Processing: chapter 13, Continuous Signal Processing: The Fourier Series and chapter 8, The Discrete Fourier Transform.
- Osgood, B., The Fourier Transform and its Applications, lecture notes for EE 261, Stanford University. Chapter 1 covers Fourier series, orthogonality, convergence and the Gibbs phenomenon.
- Gibbs, J. W. (1899), Fourier's Series. Nature, 59, 606. And Hewitt, E. and Hewitt, R. E. (1979), The Gibbs-Wilbraham phenomenon: an episode in Fourier analysis. Archive for History of Exact Sciences, 21, 129–160. The overshoot and its history, including Wilbraham's 1848 description.
- Lanczos, C. (1956), Applied Analysis, Prentice Hall. The sigma factors for reducing Gibbs overshoot.