Skip to main content

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 unwanted noise that comes with it. It says how clearly a signal stands out from the background. It is usually given in decibels: 0 dB means the signal and noise are equally strong, and every extra 10 dB makes the signal ten times stronger in power.

A sine wave buried in random noise, and the same signal after averaging 16 repeated sweeps; below, the power spectrum shows the signal peak standing above a noise floor that drops as sweeps are averaged

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.

Key takeaways
  • SNR = signal power ÷ noise power. In decibels it is 10log⁡10(Ps/Pn)10 \log_{10}(P_s/P_n), or 20log⁡1020 \log_{10} 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 MM repeats of a signal improves the SNR by 10log⁡10M10 \log_{10} M dB: about 3 dB per doubling.
  • An ideal NN-bit converter has an SNR of about 6.02N+1.766.02N + 1.76 dB.

The signal-to-noise ratio formula​

As a plain ratio of powers:

SNR=PsignalPnoise\text{SNR} = \frac{P_\text{signal}}{P_\text{noise}}

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):

SNRdB=10log⁡10 ⁣(PsPn)=20log⁡10 ⁣(As,rmsAn,rms)\text{SNR}_\text{dB} = 10 \log_{10}\!\left(\frac{P_s}{P_n}\right) = 20 \log_{10}\!\left(\frac{A_{s,\text{rms}}}{A_{n,\text{rms}}}\right)

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 log⁡(x2)=2log⁡(x)\log(x^2) = 2\log(x), 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.

A scale of SNR values from 0 to 60 dB with the matching power ratio and RMS amplitude ratio below each one: 20 dB is a power ratio of 100 and an amplitude ratio of 10, 3 dB doubles the power and 6 dB doubles the amplitude

To go back from decibels to a ratio, undo the logarithm:

PsPn=10 SNRdB/10,AsAn=10 SNRdB/20\frac{P_s}{P_n} = 10^{\,\text{SNR}_\text{dB}/10}, \qquad \frac{A_s}{A_n} = 10^{\,\text{SNR}_\text{dB}/20}

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 knowWorkingSNR
Signal power 2 mW, noise power 0.02 mW10log⁡10(2/0.02)=10log⁡10(100)10 \log_{10}(2 / 0.02) = 10 \log_{10}(100)20 dB (power ratio 100)
Signal 1 V RMS, noise 10 mV RMS20log⁡10(1/0.01)=20log⁡10(100)20 \log_{10}(1 / 0.01) = 20 \log_{10}(100)40 dB (amplitude ratio 100, power ratio 10,000)
Sine wave with a 0.5 V peak, noise 1 V RMSSignal RMS is 0.5/2=0.3540.5/\sqrt{2} = 0.354 V, so 20log⁡10(0.354/1)20 \log_{10}(0.354 / 1)−9.0 dB (power ratio 0.125)
An SNR of 30 dBPower ratio 1030/1010^{30/10}, amplitude ratio 1030/2010^{30/20}1,000 : 1 in power, 31.6 : 1 in amplitude
Signal −50 dBm, noise floor −80 dBm−50−(−80)-50 - (-80)30 dB

Noise-to-signal ratio and other forms​

  • Noise-to-signal ratio (NSR) is the inverse, Pn/PsP_n/P_s. 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 μ/σ\mu/\sigma: the mean divided by the standard deviation of the noise. It is an amplitude ratio, so it converts to dB with 20log⁡1020 \log_{10}.
  • Peak instead of RMS. Some fields (pulse detection, imaging, radar) use the peak signal rather than its RMS. A sine wave's peak is 2\sqrt{2} 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:

FieldThresholdWhere it comes from
Seeing a detail in an imageSNR of about 5 (amplitude)The Rose criterion (Rose, 1948)
Analytical chemistry, chromatography3 : 1 (sometimes 2 : 1) to detect a peak; 10 : 1 to quantify itICH Q2 guideline: limit of detection (LOD) and limit of quantitation (LOQ)
An ideal 16-bit audio converter (CD)98 dB6.02×16+1.766.02 \times 16 + 1.76 for a full-scale sine (Kester, MT-001)
An ideal 12-bit converter74 dBThe same formula
A data link at 0 dB SNRUp to 1 bit per second per hertz of bandwidthShannon capacity, log⁡2(1+1)\log_2(1 + 1)

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​

FieldWhat "signal" and "noise" areUsual form
Audio and electronicsA 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-weighteddB, power ratio. Often quoted with SINAD or THD+N (below)
Imaging and camerasMean pixel level vs the standard deviation of pixel noise (shot, read and dark noise)μ/σ\mu/\sigma, or dB with 20log⁡1020\log_{10}
Image and video compressionThe largest possible pixel value vs the error after compression: peak signal-to-noise ratio (PSNR)PSNR=10log⁡10(MAX2/MSE)\text{PSNR} = 10 \log_{10}(\text{MAX}^2/\text{MSE}), with MAX = 255 for 8-bit images
Radio, Wi-Fi, cable and DSLReceived signal strength vs the noise floor in the channel's bandwidthdB, often RSSI in dBm minus the noise floor in dBm. Cable modems report it per channel ("downstream SNR")
Chromatography and spectroscopyPeak height vs the baseline noise next to itA 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:

Ps=Pon−Poff,SNR=Pon−PoffPoffP_s = P_\text{on} - P_\text{off}, \qquad \text{SNR} = \frac{P_\text{on} - P_\text{off}}{P_\text{off}}

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:

A sketch of a power spectrum with a ragged noise floor and one signal peak. The signal power is the sum of the peak's bins, the noise power is the noise density times the shaded measurement bandwidth, and a note warns that the peak's height above the floor is not the SNR

Pn=∫f1f2Sn(f) df≈N0×BP_n = \int_{f_1}^{f_2} S_n(f)\, df \approx N_0 \times B

where Sn(f)S_n(f) is the noise PSD, N0N_0 its average level in units² per hertz, and B=f2−f1B = f_2 - f_1 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 NN-point FFT and no window, the peak sits about 10log⁡10(N/2)10 \log_{10}(N/2) 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 kTBkTB, about −174 dBm per hertz at room temperature (290 K), so a 20 MHz radio channel starts with a noise floor of about −174+10log⁡10(2×107)≈−101-174 + 10\log_{10}(2 \times 10^7) \approx -101 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 10log⁡10(512/50)≈1010\log_{10}(512/50) \approx 10 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 MM repeats keeps the signal the same and divides the noise power by MM:

SNRM=M×SNR1⟺SNRM,dB=SNR1,dB+10log⁡10M\text{SNR}_M = M \times \text{SNR}_1 \quad\Longleftrightarrow\quad \text{SNR}_{M,\text{dB}} = \text{SNR}_{1,\text{dB}} + 10 \log_{10} M

In amplitude, the noise RMS falls by M\sqrt{M}. 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 MM neighbouring samples reduces white noise by M\sqrt{M} 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":

FigureRatio ofIncludes harmonics and spurs?
SNRSignal 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 distortionYes
THD+NEverything except the signal, to the signal: the inverse of SINAD, often in % or as a negative dB valueYes
Dynamic rangeThe 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 spurOnly the largest spur
ENOB (effective number of bits)SINAD, expressed as the bits of an ideal converter with the same SINADYes

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 NN bits adds quantisation noise, and the best SNR it can reach is:

SNRideal≈6.02 N+1.76 dB\text{SNR}_\text{ideal} \approx 6.02\,N + 1.76 \text{ dB}

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:

ENOB=SINAD−1.766.02\text{ENOB} = \frac{\text{SINAD} - 1.76}{6.02}

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 BB and white Gaussian noise is:

C=Blog⁡2(1+SNR)C = B \log_2(1 + \text{SNR})

with CC in bits per second, BB 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 20×106×log⁡2(1001)≈19920 \times 10^6 \times \log_2(1001) \approx 199 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​

  • Mixing power and amplitude dB. Using 10log⁡1010\log_{10} on a voltage ratio halves the answer; using 20log⁡1020\log_{10} 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 a decibel or more. Average more data, or several measurements, before trusting the last decimal place.

How to measure and chart SNR in JavaScript, React or Angular​

SciChart.js redraws a signal and its spectrum with WebGL and WebGPU fast enough to follow 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 to read values, 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:

// 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 };
}

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 XyDataSeries with appendRange on both charts. The time chart uses FastLineRenderableSeries with 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 a VerticalLineAnnotation marks 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 signal and spectrum chart · React signal and spectrum chart · Angular signal and spectrum 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 chart 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 (2005), ICH Q2(R1): Validation of Analytical Procedures: Text and Methodology. Signal-to-noise ratios of 3:1 or 2:1 for the detection limit and 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.