Signal-to-Noise Ratio (SNR)
What is signal-to-noise ratio?
Signal-to-noise ratio (SNR, also written S/N) is the power of a wanted signal divided by the power of the noise that comes with it. It says how clearly a signal stands out. It is usually given in decibels: 0 dB means the signal and noise are equally strong, and each extra 10 dB is ten times more signal power.

A weak signal in noise before and after averaging (top), and its power spectrum with the signal peak and noise floor (bottom). Try the interactive version.
- SNR = signal power ÷ noise power. In decibels it is , or of a ratio of RMS amplitudes.
- Higher is better. 0 dB means equal power; a negative SNR means the noise is stronger than the signal.
- Noise power grows with bandwidth, so an SNR is only meaningful with its bandwidth stated. Filtering out unused bandwidth raises it.
- Averaging repeats of a signal improves the SNR by dB: about 3 dB per doubling.
- An ideal -bit converter has an SNR of about dB.
The signal-to-noise ratio formula
As a plain ratio of powers:
Both powers must be measured in the same place, in the same units and over the same bandwidth. For a voltage, current or a list of samples, "power" means the mean square: square each value and take the average. Its square root is the RMS (root mean square) value.
Because SNRs range from below 1 to many millions, they are almost always written in decibels (dB):
Why 10 log for power and 20 log for amplitude?
The decibel is defined for power ratios, with a factor of 10. Power is proportional to amplitude squared, and , so a ratio of RMS amplitudes (volts, pascals, pixel values) takes a factor of 20. Both forms give the same number of dB for the same situation: an amplitude ratio of 10 is a power ratio of 100, and both are 20 dB.
To go back from decibels to a ratio, undo the logarithm:
When both powers are already in dB units (dBm, dBV or dBFS), the SNR is a subtraction: a signal at −50 dBm over noise at −80 dBm has an SNR of 30 dB.
Worked examples: how to calculate SNR
| You know | Working | SNR |
|---|---|---|
| Signal power 2 mW, noise power 0.02 mW | 20 dB (power ratio 100) | |
| Signal 1 V RMS, noise 10 mV RMS | 40 dB (amplitude ratio 100, power ratio 10,000) | |
| Sine wave with a 0.5 V peak, noise 1 V RMS | Signal RMS is V, so | −9.0 dB (power ratio 0.125) |
| An SNR of 30 dB | Power ratio , amplitude ratio | 1,000 : 1 in power, 31.6 : 1 in amplitude |
| Signal −50 dBm, noise floor −80 dBm | 30 dB |
Noise-to-signal ratio and other forms
- Noise-to-signal ratio (NSR) is the inverse, . In dB only the sign flips: an SNR of 20 dB is an NSR of −20 dB. Lower is better.
- Mean over standard deviation. For a signal that is a steady level, such as a pixel in an image or a repeated reading, SNR is often defined as : the mean divided by the standard deviation of the noise. It is an amplitude ratio, so it converts to dB with .
- Peak instead of RMS. Some fields (pulse detection, imaging, radar) use the peak signal rather than its RMS. A sine wave's peak is times its RMS, so a peak-based SNR is about 3 dB higher. Say which you used.
What is a good signal-to-noise ratio?
A high SNR means a clean signal that is easy to measure or decode. A low SNR means the noise is close to the signal, and below 0 dB it is stronger than the signal. Higher is better, but how much you need depends on the task. Published figures, each with its source:
| Field | Threshold | Where it comes from |
|---|---|---|
| Seeing a detail in an image | SNR of about 5 (amplitude) | The Rose criterion (Rose, 1948) |
| Analytical chemistry, chromatography | 3 : 1 to detect a peak; at least 10 : 1 to quantify it | ICH Q2(R2) guideline: limit of detection (LOD) and limit of quantitation (LOQ) |
| An ideal 16-bit audio converter (CD) | 98 dB | for a full-scale sine (Kester, MT-001) |
| An ideal 12-bit converter | 74 dB | The same formula |
| A data link at 0 dB SNR | Up to 1 bit per second per hertz of bandwidth | Shannon capacity, |
For Wi-Fi, cable modems and other digital links, the SNR needed rises with the data rate: each step up in modulation (for example from 64-QAM to 256-QAM) packs more bits into each symbol and needs a cleaner signal. Equipment makers publish the minimum SNR for each rate; use those figures for your hardware rather than a single "good" number.
SNR in different fields
Each field defines signal and noise in its own way, so check the convention before comparing figures.
| Field | What "signal" and "noise" are | Usual form |
|---|---|---|
| Audio and electronics | A reference tone (often full scale or 1 kHz) vs the noise with no input, over the audio band (20 Hz to 20 kHz), sometimes A-weighted | dB, power ratio. Often quoted with SINAD or THD+N (below) |
| Imaging and cameras | Mean pixel level vs the standard deviation of pixel noise (shot, read and dark noise) | , or dB with |
| Image and video compression | The largest possible pixel value vs the error after compression: peak signal-to-noise ratio (PSNR) | , with MAX = 255 for 8-bit images |
| Radio, Wi-Fi, cable and DSL | Received signal strength vs the noise floor in the channel's bandwidth | dB, often RSSI in dBm minus the noise floor in dBm. Cable modems report it per channel ("downstream SNR") |
| Chromatography and spectroscopy | Peak height vs the baseline noise next to it | A ratio such as 10 : 1. Conventions for measuring the noise (peak-to-peak or RMS) differ between pharmacopoeias, so state which |
Outside engineering, "signal-to-noise ratio" is also an idiom for how much useful information there is among the distraction around it, with no number attached.
How to measure signal-to-noise ratio
There are two common ways.
Method 1: signal on, signal off
Measure the RMS (or power) with the signal present, then again with the signal switched off but everything else the same, which gives the noise. Signal and noise powers add when the noise is uncorrelated, so:
When the SNR is high, the subtraction makes little difference; when it's near 0 dB, leaving it out overstates the SNR.
Method 2: from a spectrum
Take an FFT or a power spectral density of the signal. The signal power is the sum of the bins in its peak. The noise power is the noise floor's density integrated over the bandwidth you care about:
where is the noise PSD, its average level in units² per hertz, and the bandwidth. A spectrum makes it easy to leave out hum, harmonics or interference you want to count separately (they belong in SINAD, below).
Don't read the SNR off the height of the peak above the floor. Each FFT bin holds only the noise in its own narrow band, so the floor drops 3 dB every time you double the FFT length, while a sine's peak stays put. With an -point FFT, no window and a tone centred on a bin, the peak sits about dB further above the floor than the true SNR: 27 dB for a 1,024-point FFT. That gap is the FFT's processing gain. For example, one 1,024-point sweep of the −9 dB sine from the worked examples puts the peak about 18 dB above the floor: 27 dB higher than its true SNR.
How to improve the signal-to-noise ratio
You can make the signal bigger, or the noise smaller.
Narrow the bandwidth: noise power scales with bandwidth
For white noise, which has the same power in every hertz, noise power is proportional to bandwidth. Halve the bandwidth and you halve the noise power: +3 dB of SNR. Thermal (Johnson–Nyquist) noise in a resistor is the textbook case: its available power is , about −174 dBm per hertz at room temperature (290 K), so a 20 MHz radio channel starts with a noise floor of about dBm before any amplifier adds more.
So the first step to a better SNR is to keep only the bandwidth the signal uses. A low-pass filter that cuts a 512 Hz band down to 50 Hz improves the SNR by dB, as long as the signal itself lies below 50 Hz. Cut into the signal and you lose signal power too. The same principle is behind the anti-aliasing filter before an analogue-to-digital converter: noise above the Nyquist frequency would otherwise fold down into the band you keep.
Average repeated measurements: SNR grows with √M
When a signal repeats exactly (a triggered sweep, a stimulus and its response, an NMR or radar pulse) and the noise in each repeat is random and independent, averaging repeats keeps the signal the same and divides the noise power by :
In amplitude, the noise RMS falls by . That's +3 dB for each doubling: 4 averages give +6 dB, 16 give +12 dB, 64 give +18 dB and 256 give +24 dB. The returns diminish, because each further 3 dB costs as many repeats as all the ones before.
Averaging only works if the repeats line up in time (they are coherent). Jitter in the trigger smears and shrinks the signal. Noise that is the same in every repeat, such as mains hum locked to the trigger, is not reduced at all. A moving average applies the same idea along a single record: averaging neighbouring samples reduces white noise by in amplitude, at the cost of smoothing the signal.
Other ways
- More signal: a stronger source, a more sensitive sensor, more light or a longer exposure, using the converter's full range.
- Less noise at the source: shielding, twisted pairs and short cables against interference; cooling a sensor to cut thermal and dark noise; a low-noise amplifier as the first stage, since the first stage's noise dominates.
- Correlation: when you know the shape of the signal, correlating against it (a matched filter) concentrates its energy and recovers signals far below the noise. Spread-spectrum radio and radar rely on this; see autocorrelation.
SNR vs SINAD, THD+N, dynamic range and ENOB
Data sheets for converters, amplifiers and audio equipment quote several related figures. They differ in what counts as "noise":
| Figure | Ratio of | Includes harmonics and spurs? |
|---|---|---|
| SNR | Signal power to noise power, excluding the harmonics of the test tone (and DC) | No |
| SINAD (signal-to-noise-and-distortion) | Signal power to everything else: noise plus distortion | Yes |
| THD+N | Everything except the signal, to the signal: the inverse of SINAD, often in % or as a negative dB value | Yes |
| Dynamic range | The largest signal the system can handle to its noise floor (or its smallest detectable signal) | Depends on the definition |
| SFDR (spurious-free dynamic range) | The signal to the largest single spur | Only the largest spur |
| ENOB (effective number of bits) | SINAD, expressed as the bits of an ideal converter with the same SINAD | Yes |
SNR describes an actual signal; dynamic range describes the system's limits. A recorder with 100 dB of dynamic range playing a quiet passage 40 dB below full scale gives at most about 60 dB of SNR.
PSNR (peak signal-to-noise ratio) compares the largest possible value, not the signal's actual power, with the mean squared error (MSE) between an original and a processed copy. It is the usual score for lossy image and video compression, and for comparing denoising methods.
SNR of an ideal converter: 6.02N + 1.76 dB
Rounding a full-scale sine wave to bits adds quantisation noise, and the best SNR it can reach is:
measured over the full band from 0 Hz to half the sample rate. That's 74.0 dB for 12 bits, 98.1 dB for 16 bits and 146.2 dB for 24 bits. Real converters fall short, so their measured SINAD is turned into an effective number of bits:
A 16-bit converter with a measured SINAD of 86 dB has an ENOB of about 14.0 bits. Oversampling helps for the bandwidth reason above: sampling 4 times faster than needed and filtering back to the original band spreads the same quantisation noise over 4 times the bandwidth, then removes three quarters of it, for +6 dB.
SNR and channel capacity: the Shannon–Hartley theorem
SNR also sets the limit on how much data a channel can carry. Shannon showed that the maximum error-free data rate of a channel with bandwidth and white Gaussian noise is:
with in bits per second, in hertz and SNR as a power ratio (not dB). A 20 MHz channel at 30 dB (a ratio of 1,000) can carry at most Mbit/s. Doubling the bandwidth doubles the capacity, while doubling the SNR (+3 dB) adds only about one bit per second per hertz at high SNR. So faster Wi-Fi and cellular standards widen their channels and add antennas.
Common SNR mistakes
Most SNR mistakes come from mixing power and amplitude, or from measuring signal and noise in different bandwidths.
- Mixing power and amplitude dB. Using on a voltage ratio halves the answer; using on a power ratio doubles it. Square amplitudes first, or use 20 log.
- Not stating the bandwidth. "SNR = 90 dB" means nothing without "over 20 Hz to 20 kHz" or "in a 1 Hz bin". The same system gives a different number in a different bandwidth.
- Too short a measurement. An SNR estimated from a few hundred noise samples can be out by about a third of a decibel (a standard error of about 0.34 dB from 300 samples of white noise), and by more if the noise isn't white. Average more data, or several measurements, before trusting the last decimal place.
How to measure and chart SNR in JavaScript, React or Angular
The demo averages up to 256 one-second sweeps of 1,024 samples, takes the FFT of the average, and recomputes the SNR each time you move a slider. Choose a sine or a pulse, set the signal amplitude and noise level, and move the Averages slider: each doubling adds about 3 dB to the measured SNR in the readout. Then pick a low-pass filter to cut the bandwidth. On the spectrum, watch the noise floor fall while the signal peak stays put. Hover over the spectrum to read the floor and the peak; scroll to zoom, drag to pan, and double-click to reset.
Here is the code. The live demo averages up to 256 sweeps of seeded noise, filters in the frequency domain with a radix-2 FFT and measures the SNR from the samples; the React and Angular versions show the core pattern with your own recorded sweeps:
- JavaScript
- React
- Angular
// A signal-to-noise ratio (SNR) lab in JavaScript with SciChart.js: bury a signal in noise, then win it back
// by averaging repeated sweeps and by narrowing the bandwidth with a low-pass filter. The DSP functions below are
// plain JavaScript with no dependencies, so you can use them anywhere.
const SAMPLE_RATE = 1024; // samples per second, so the spectrum runs from 0 Hz to the Nyquist frequency, 512 Hz
const SWEEP_LENGTH = 1024; // samples per sweep (1 second), a power of 2 for the FFT. Bin width = 1 Hz
const MAX_SWEEPS = 256; // the most sweeps the demo averages
const SINE_FREQUENCY = 20; // Hz, exactly on an FFT bin, so the sine's power sits in one bin
// Iterative radix-2 Cooley-Tukey FFT, in place. re and im hold the real and imaginary parts;
// their length must be a power of 2. Afterwards, re[k] and im[k] hold frequency bin k.
function fft(re, im) {
const n = re.length;
// 1. Reorder the samples by bit-reversed index
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) {
[re[i], re[j]] = [re[j], re[i]];
[im[i], im[j]] = [im[j], im[i]];
}
}
// 2. Combine pairs of smaller DFTs into bigger ones with butterflies: a + w*b and a - w*b
for (let size = 2; size <= n; size *= 2) {
const half = size / 2;
const step = (-2 * Math.PI) / size;
for (let start = 0; start < n; start += size) {
for (let k = 0; k < half; k++) {
const wr = Math.cos(step * k);
const wi = Math.sin(step * k);
const a = start + k;
const b = a + half;
const tr = re[b] * wr - im[b] * wi;
const ti = re[b] * wi + im[b] * wr;
re[b] = re[a] - tr;
im[b] = im[a] - ti;
re[a] += tr;
im[a] += ti;
}
}
}
}
// Seeded random numbers, so the noise is the same every time the page loads
function makeRandom(seed) {
let state = seed;
const uniform = () => {
state = (state * 16807) % 2147483647;
return (state - 0.5) / 2147483647; // strictly between 0 and 1
};
// Box-Muller: two uniform numbers make one Gaussian (normal) number with mean 0 and standard deviation 1
return () => Math.sqrt(-2 * Math.log(uniform())) * Math.cos(2 * Math.PI * uniform());
}
// The clean signal, with a peak amplitude of 1: a sine wave, or a short Gaussian pulse in the middle of the sweep
function makeCleanSignal(kind) {
const values = new Float64Array(SWEEP_LENGTH);
for (let i = 0; i < SWEEP_LENGTH; i++) {
const t = i / SAMPLE_RATE;
values[i] = kind === "pulse" ? Math.exp(-0.5 * Math.pow((t - 0.5) / 0.01, 2)) : Math.sin(2 * Math.PI * SINE_FREQUENCY * t);
}
return values;
}
// MAX_SWEEPS sweeps of white Gaussian noise with an RMS of 1. Each sweep gets fresh, independent noise,
// as it would if you triggered a measurement again and again on a repeating signal.
function makeNoiseSweeps(seed) {
const gaussian = makeRandom(seed);
const sweeps = [];
for (let s = 0; s < MAX_SWEEPS; s++) {
const sweep = new Float64Array(SWEEP_LENGTH);
for (let i = 0; i < SWEEP_LENGTH; i++) sweep[i] = gaussian();
sweeps.push(sweep);
}
return sweeps;
}
// Coherent averaging: the mean of the first `count` noise sweeps, scaled to the noise RMS. The signal is the same
// in every sweep, so averaging leaves it unchanged; uncorrelated noise shrinks to 1/sqrt(count) of its RMS.
function averageNoise(noiseSweeps, count, noiseRms) {
const average = new Float64Array(SWEEP_LENGTH);
for (let s = 0; s < count; s++) {
const sweep = noiseSweeps[s];
for (let i = 0; i < SWEEP_LENGTH; i++) average[i] += sweep[i];
}
for (let i = 0; i < SWEEP_LENGTH; i++) average[i] *= noiseRms / count;
return average;
}
// An ideal ("brick-wall") low-pass filter, applied offline in the frequency domain: FFT, set every bin above the
// cutoff to zero, inverse FFT. With 1 Hz bins it keeps exactly the noise between 0 Hz and the cutoff.
function idealLowPass(samples, cutoffHz) {
const n = samples.length;
const lastBin = Math.round((cutoffHz * n) / SAMPLE_RATE);
const re = Float64Array.from(samples);
const im = new Float64Array(n);
fft(re, im);
for (let k = lastBin + 1; k < n - lastBin; k++) {
re[k] = 0; // bin k and its mirror image, n - k (the negative frequency)
im[k] = 0;
}
// Inverse FFT by conjugating, transforming and conjugating again, then dividing by n; the result is real
for (let k = 0; k < n; k++) im[k] = -im[k];
fft(re, im);
for (let i = 0; i < n; i++) re[i] /= n;
return re;
}
// The fraction of white noise's power a cutoff lets through: (2K + 1) of the n two-sided bins, about cutoff / (fs/2)
function noiseFractionKept(cutoffHz) {
const lastBin = Math.min(SWEEP_LENGTH / 2, Math.round((cutoffHz * SWEEP_LENGTH) / SAMPLE_RATE));
return lastBin >= SWEEP_LENGTH / 2 ? 1 : (2 * lastBin + 1) / SWEEP_LENGTH;
}
// Mean square = power, in (signal units)^2. Its square root is the RMS.
function meanSquare(values) {
let sum = 0;
for (let i = 0; i < values.length; i++) sum += values[i] * values[i];
return sum / values.length;
}
// SNR from two powers: as a ratio, and in decibels, 10 log10(Ps / Pn)
const snrDb = (signalPower, noisePower) => 10 * Math.log10(signalPower / noisePower);
// One-sided power spectrum with no window: the power in each 1 Hz bin. A sine of amplitude A on a bin shows as
// A^2 / 2; white noise of power P spreads over the n/2 bins, so each bin holds about P / (n/2). (Parseval's theorem:
// the bins add up to the mean square.)
function powerSpectrum(samples) {
const n = samples.length;
const re = Float64Array.from(samples);
const im = new Float64Array(n);
fft(re, im);
const power = new Float64Array(n / 2 + 1);
for (let k = 0; k <= n / 2; k++) {
const oneSided = k === 0 || k === n / 2 ? 1 : 2; // fold the negative frequencies in
power[k] = (oneSided * (re[k] * re[k] + im[k] * im[k])) / (n * n);
}
return power;
}
async function createSnrCharts(timeDiv, spectrumDiv) {
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
EAutoRange,
ENumericFormat,
ELabelPlacement,
XyDataSeries,
FastLineRenderableSeries,
HorizontalLineAnnotation,
VerticalLineAnnotation,
LegendModifier,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
const toDb = (power) => 10 * Math.log10(Math.max(power, 1e-15));
const time = Array.from({ length: SWEEP_LENGTH }, (_, i) => i / SAMPLE_RATE);
const frequencies = Array.from({ length: SWEEP_LENGTH / 2 }, (_, k) => k + 1); // bins 1 to 512 Hz (a log axis can't show 0 Hz)
// --- Chart 1: the signal in time. One raw sweep, the averaged and filtered result, and the clean signal ---
const timeChart = await SciChartSurface.create(timeDiv, { theme: new SciChartJsNavyTheme() });
timeChart.sciChartSurface.xAxes.add(new NumericAxis(timeChart.wasmContext, { axisTitle: "Time (s)", labelPrecision: 1 }));
const amplitudeAxis = new NumericAxis(timeChart.wasmContext, { axisTitle: "Amplitude", autoRange: EAutoRange.Never });
timeChart.sciChartSurface.yAxes.add(amplitudeAxis);
const rawSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "One raw sweep", dataIsSortedInX: true });
const outputSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Averaged + filtered", dataIsSortedInX: true });
const cleanSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Clean signal", dataIsSortedInX: true });
timeChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: rawSeries, stroke: "#50C7E066", strokeThickness: 1 }),
new FastLineRenderableSeries(timeChart.wasmContext, { dataSeries: outputSeries, stroke: "#F48420", strokeThickness: 2 }),
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: cleanSeries,
stroke: "#FFFFFFCC",
strokeThickness: 1.5,
strokeDashArray: [6, 4]
})
);
// Hover for values, scroll to zoom, drag to pan, double-click to reset
timeChart.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// --- Chart 2: the power spectrum in dB, on a log frequency axis, with the noise floor and signal peak marked ---
const spectrumChart = await SciChartSurface.create(spectrumDiv, { theme: new SciChartJsNavyTheme() });
spectrumChart.sciChartSurface.xAxes.add(
new LogarithmicAxis(spectrumChart.wasmContext, {
axisTitle: "Frequency (Hz)",
logBase: 10,
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 3,
autoTicks: false, // a labelled gridline at 1, 10 and 100 Hz, and minor gridlines between
majorDelta: 1,
minorDelta: 1,
visibleRange: new NumberRange(1, SAMPLE_RATE / 2)
})
);
spectrumChart.sciChartSurface.yAxes.add(
new NumericAxis(spectrumChart.wasmContext, {
axisTitle: "Power per bin (dB)",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-90, 10),
labelPrecision: 0
})
);
const rawSpectrum = new XyDataSeries(spectrumChart.wasmContext, { dataSeriesName: "One raw sweep", dataIsSortedInX: true });
const outputSpectrum = new XyDataSeries(spectrumChart.wasmContext, { dataSeriesName: "Averaged + filtered", dataIsSortedInX: true });
spectrumChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(spectrumChart.wasmContext, { dataSeries: rawSpectrum, stroke: "#50C7E066", strokeThickness: 1 }),
new FastLineRenderableSeries(spectrumChart.wasmContext, { dataSeries: outputSpectrum, stroke: "#F48420", strokeThickness: 2 })
);
const peakLine = new HorizontalLineAnnotation({
y1: 0,
stroke: "#FFFFFFAA",
strokeDashArray: [6, 4],
showLabel: true,
labelPlacement: ELabelPlacement.TopRight
});
const floorLine = new HorizontalLineAnnotation({
y1: -60,
stroke: "#68BCAE",
strokeDashArray: [6, 4],
showLabel: true,
labelPlacement: ELabelPlacement.BottomLeft, // below the line, where the log axis leaves room
axisLabelFill: "#68BCAE"
});
const cutoffLine = new VerticalLineAnnotation({
x1: SAMPLE_RATE / 2,
stroke: "#F48420",
strokeDashArray: [2, 4],
showLabel: true,
labelPlacement: ELabelPlacement.TopLeft,
axisLabelFill: "#F48420"
});
spectrumChart.sciChartSurface.annotations.add(peakLine, floorLine, cutoffLine);
spectrumChart.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// The noise is made once and reused, so moving a slider changes only what you asked it to
const noiseSweeps = makeNoiseSweeps(42);
const cleanSignals = { sine: makeCleanSignal("sine"), pulse: makeCleanSignal("pulse") };
// Recompute everything from the settings: { signal, amplitude, noiseRms, averages, cutoff }
// cutoff is in Hz; SAMPLE_RATE / 2 means no filter. Returns the SNRs for the readout.
const update = (settings) => {
const { amplitude, noiseRms, averages, cutoff } = settings;
const clean = cleanSignals[settings.signal].map((v) => v * amplitude);
const filtered = cutoff < SAMPLE_RATE / 2;
// One raw sweep: signal + noise, no averaging, no filter
const raw = clean.map((v, i) => v + noiseRms * noiseSweeps[0][i]);
// The processed result. Averaging and filtering are linear, so the signal part and the noise part can be
// processed separately and added: that's also how you measure the noise, with the signal switched off.
const signalPart = filtered ? idealLowPass(clean, cutoff) : clean;
const averagedNoise = averageNoise(noiseSweeps, averages, noiseRms);
const noisePart = filtered ? idealLowPass(averagedNoise, cutoff) : averagedNoise;
const output = signalPart.map((v, i) => v + noisePart[i]);
// Measured SNRs, from the samples
const signalPower = meanSquare(signalPart);
const rawSnr = meanSquare(clean) / meanSquare(raw.map((v, i) => v - clean[i]));
const measuredSnr = signalPower / meanSquare(noisePart);
// Predicted SNR: noise power falls by the number of averages, and by the share of the bandwidth kept
const predictedNoisePower = ((noiseRms * noiseRms) / averages) * noiseFractionKept(cutoff);
const predictedSnr = signalPower / predictedNoisePower;
// Update the charts
rawSeries.clear();
rawSeries.appendRange(time, Array.from(raw));
outputSeries.clear();
outputSeries.appendRange(time, Array.from(output));
cleanSeries.clear();
cleanSeries.appendRange(time, Array.from(clean));
const range = amplitude + 3 * noiseRms;
amplitudeAxis.visibleRange = new NumberRange(-range, range);
rawSpectrum.clear();
rawSpectrum.appendRange(frequencies, Array.from(powerSpectrum(raw).subarray(1), toDb));
outputSpectrum.clear();
outputSpectrum.appendRange(frequencies, Array.from(powerSpectrum(output).subarray(1), toDb));
// The signal's highest bin, and the noise floor: the noise power expected in each 1 Hz bin
const peakDb = toDb(Math.max(...powerSpectrum(signalPart)));
const floorDb = toDb((noiseRms * noiseRms) / averages / (SWEEP_LENGTH / 2));
peakLine.y1 = peakDb;
peakLine.labelValue = `Signal peak ${peakDb.toFixed(1)} dB`;
floorLine.y1 = floorDb;
floorLine.labelValue = `Noise floor per bin ${floorDb.toFixed(1)} dB`;
cutoffLine.isHidden = !filtered;
cutoffLine.x1 = cutoff;
cutoffLine.labelValue = `Low-pass ${cutoff} Hz`;
return { rawSnr, measuredSnr, predictedSnr };
};
return { update };
}
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
XyDataSeries,
FastLineRenderableSeries,
LegendModifier,
SciChartJsNavyTheme
} from "scichart";
// Power is the mean square of the samples; SNR in dB is 10 log10 of a power ratio
const meanSquare = (values: number[]) => values.reduce((sum, v) => sum + v * v, 0) / values.length;
const snrDb = (signalPower: number, noisePower: number) => 10 * Math.log10(signalPower / noisePower);
// Coherent averaging: the mean of repeated, time-aligned sweeps of the same signal
const averageSweeps = (sweeps: number[][]) =>
sweeps[0].map((_, i) => sweeps.reduce((sum, sweep) => sum + sweep[i], 0) / sweeps.length);
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
// Your data: repeated sweeps of a signal, and one recording with the signal switched off
const { time, sweeps, noiseOnly } = getYourSweeps();
const noisePower = meanSquare(noiseOnly);
const signalPower = meanSquare(sweeps[0]) - noisePower; // signal and noise powers add
const rawSnr = snrDb(signalPower, noisePower);
const averagedSnr = snrDb(signalPower, noisePower / sweeps.length); // independent noise power falls by N
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme(),
title: `SNR ${rawSnr.toFixed(1)} dB raw, ${averagedSnr.toFixed(1)} dB after ${sweeps.length} averages`
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Amplitude" }));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: time, yValues: sweeps[0], dataSeriesName: "One raw sweep" }),
stroke: "#50C7E066"
}),
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: time, yValues: averageSweeps(sweeps), dataSeriesName: "Averaged" }),
stroke: "#F48420",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(new LegendModifier({ showCheckboxes: true }));
return { sciChartSurface };
};
export const SnrChart = () => <SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />;
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
XyDataSeries,
FastLineRenderableSeries,
LegendModifier,
SciChartJsNavyTheme
} from "scichart";
// Power is the mean square of the samples; SNR in dB is 10 log10 of a power ratio
const meanSquare = (values: number[]) => values.reduce((sum, v) => sum + v * v, 0) / values.length;
const snrDb = (signalPower: number, noisePower: number) => 10 * Math.log10(signalPower / noisePower);
// Coherent averaging: the mean of repeated, time-aligned sweeps of the same signal
const averageSweeps = (sweeps: number[][]) =>
sweeps[0].map((_, i) => sweeps.reduce((sum, sweep) => sum + sweep[i], 0) / sweeps.length);
@Component({
selector: "app-snr-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class SnrChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
// Your data: repeated sweeps of a signal, and one recording with the signal switched off
const { time, sweeps, noiseOnly } = getYourSweeps();
const noisePower = meanSquare(noiseOnly);
const signalPower = meanSquare(sweeps[0]) - noisePower; // signal and noise powers add
const rawSnr = snrDb(signalPower, noisePower);
const averagedSnr = snrDb(signalPower, noisePower / sweeps.length); // independent noise power falls by N
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme(),
title: `SNR ${rawSnr.toFixed(1)} dB raw, ${averagedSnr.toFixed(1)} dB after ${sweeps.length} averages`
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Amplitude" }));
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: time, yValues: sweeps[0], dataSeriesName: "One raw sweep" }),
stroke: "#50C7E066"
}),
new FastLineRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: time, yValues: averageSweeps(sweeps), dataSeriesName: "Averaged" }),
stroke: "#F48420",
strokeThickness: 2
})
);
sciChartSurface.chartModifiers.add(new LegendModifier({ showCheckboxes: true }));
return { sciChartSurface };
};
}
Key points:
- SNR from samples: power is the mean square, so
10 * Math.log10(signalPower / noisePower)gives the SNR in dB. The demo measures the noise the "signal off" way: averaging and filtering are linear, so it processes the noise on its own and compares it with the processed clean signal. - Two charts, one update: each control change clears and refills
XyDataSerieswithappendRangeon both charts. The time chart usesFastLineRenderableSerieswith a dashed line (strokeDashArray) for the clean signal. - The spectrum uses a LogarithmicAxis for frequency and a dB axis for power. A HorizontalLineAnnotation marks the signal peak and the predicted noise floor, with live labels (
labelValue), and aVerticalLineAnnotationmarks the filter cutoff. - The FFT, the brick-wall filter and the noise generator are plain JavaScript in the demo (a seeded random generator, so the chart is the same on every load). Swap in your own recorded sweeps to measure a real system.
See it in the demo app: JavaScript audio spectrum analyzer chart · React audio spectrum analyzer chart · Angular audio spectrum analyzer chart, a live audio waveform with its FFT spectrum and spectrogram. For a real-time medical signal, see the JavaScript ECG chart · React ECG chart · Angular ECG chart.
Go deeper: SciChart.js line series documentation, the logarithmic axis, horizontal line annotations, and the related guides in this section: power spectral density, FFT and low-pass filter.
Frequently asked questions
What is a good signal-to-noise ratio?
It depends on the job. A detail in an image needs an SNR of about 5 to be seen reliably (the Rose criterion). In analytical chemistry, a peak at 3:1 counts as detected and one at 10:1 can be quantified. An ideal 16-bit audio converter reaches about 98 dB. In general, higher is better, and the SNR only means something when its bandwidth and units are stated.
Is a higher or lower signal-to-noise ratio better?
Higher is better. A high SNR means the signal is much stronger than the noise, so it is clean and easy to measure or decode. A low SNR means the noise is close to the signal, or stronger than it when the SNR is below 0 dB, so the signal is hard to detect without averaging, filtering or a more sensitive measurement.
How do you calculate SNR in dB?
Work out the power ratio, signal over noise, then take 10 × log10 of it. If you have RMS voltages or amplitudes instead of powers, use 20 × log10 of their ratio. For example, a signal of 1 V RMS over noise of 10 mV RMS is an amplitude ratio of 100, which is 40 dB. To convert back, a power ratio is 10^(dB/10) and an amplitude ratio is 10^(dB/20).
What is the difference between signal-to-noise ratio and noise-to-signal ratio?
The noise-to-signal ratio is the inverse of the signal-to-noise ratio: noise power divided by signal power. An SNR of 100 is a noise-to-signal ratio of 0.01. In decibels only the sign changes, so an SNR of 20 dB is a noise-to-signal ratio of -20 dB. Lower is better for noise-to-signal ratio.
How does averaging improve the signal-to-noise ratio?
When a signal repeats exactly and the noise in each repetition is random and independent, averaging M repetitions leaves the signal unchanged and divides the noise power by M. The SNR improves by M as a power ratio, or the square root of M in amplitude: 10 × log10(M) dB. Each doubling of the number of averages adds about 3 dB.
How do I calculate and plot SNR in JavaScript?
Compute the power of each part as its mean square: the sum of the squared samples divided by their number. Measure the noise with the signal switched off, then SNR in dB = 10 × Math.log10(signalPower / noisePower). To plot the signal, its average and its spectrum, put the samples in XyDataSeries and draw them with FastLineRenderableSeries in SciChart.js, using a LogarithmicAxis for frequency.
Sources
- Smith, S. W. (1997), The Scientist and Engineer's Guide to Digital Signal Processing, California Technical Publishing. Chapter 2 (noise, mean and standard deviation, SNR as mean over standard deviation) and chapter 15 (moving average filters: noise reduced by the square root of the number of points).
- Kester, W. (2009), Taking the Mystery out of the Infamous Formula, "SNR = 6.02N + 1.76dB", tutorial MT-001, and Understand SINAD, ENOB, SNR, THD, THD + N, and SFDR, tutorial MT-003, Analog Devices.
- Shannon, C. E. (1949), "Communication in the Presence of Noise", Proceedings of the IRE, 37(1), pp. 10–21. Channel capacity in terms of bandwidth and SNR.
- Nyquist, H. (1928), "Thermal Agitation of Electric Charge in Conductors", Physical Review, 32, pp. 110–113, and Johnson, J. B. (1928), "Thermal Agitation of Electricity in Conductors", Physical Review, 32, pp. 97 –109. Thermal noise power proportional to bandwidth.
- Rose, A. (1948), "The Sensitivity Performance of the Human Eye on an Absolute Scale", Journal of the Optical Society of America, 38(2), pp. 196–208. The SNR of about 5 needed to detect an object in an image.
- International Council for Harmonisation (2023), ICH Q2(R2): Validation of Analytical Procedures, section 3.2.3.2. A signal-to-noise ratio of 3:1 for the detection limit and at least 10:1 for the quantitation limit.
- Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson. Quantisation noise, oversampling and spectrum analysis with the DFT.