Public
Edited
Sep 25, 2024
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function DTF(samples) {
const N = samples.length;
const frequencies = [];

// for each harmonic k...
for (let k = 0; k < N; k++) {
// ...spin the signal backwards k times (in radians)
const rate = -1 * (2 * Math.PI) * k;

let re = 0;
let im = 0;

// for every point in time...
for (let t = 0; t < N; t++) {
// How far around the circle have we gone at time = t?
const time = t / N;
const distance = rate * time;

// datapoint * e^(-i*2*pi*f) is complex, store each part
const re_part = samples[t] * Math.cos(distance);
const im_part = samples[t] * Math.sin(distance);

// add this data point's contribution
re += re_part;
im += im_part;
}

// Close to zero? You're zero.
if (Math.abs(re) < 1e-10) {
re = 0;
}
if (Math.abs(im) < 1e-10) {
im = 0;
}

// Average contribution at this harmonic
re = re / N;
im = im / N;

frequencies[k] = {
re: re,
im: im,
freq: k,
amp: Math.sqrt(re * re + im * im),
phase: (Math.atan2(im, re) * 180) / Math.PI // in degrees
};
}

return frequencies;
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more