Skip to content

Instantly share code, notes, and snippets.

@hcarter333
Created July 31, 2025 11:32
Show Gist options
  • Select an option

  • Save hcarter333/1455d02a3f97ba175557b275b25c6698 to your computer and use it in GitHub Desktop.

Select an option

Save hcarter333/1455d02a3f97ba175557b275b25c6698 to your computer and use it in GitHub Desktop.
FFT for Google Sheets from 4o
class Complex {
constructor(re, im) {
this.re = re;
this.im = im;
}
add(other) {
return new Complex(this.re + other.re, this.im + other.im);
}
sub(other) {
return new Complex(this.re - other.re, this.im - other.im);
}
mul(other) {
return new Complex(
this.re * other.re - this.im * other.im,
this.re * other.im + this.im * other.re
);
}
}
function fft(input) {
const N = input.length;
if (N <= 1) return input;
const even = fft(input.filter((_, i) => i % 2 === 0));
const odd = fft(input.filter((_, i) => i % 2 !== 0));
const output = Array(N);
for (let k = 0; k < N / 2; k++) {
const angle = (-2 * Math.PI * k) / N;
const twiddle = new Complex(Math.cos(angle), Math.sin(angle)).mul(odd[k]);
output[k] = even[k].add(twiddle);
output[k + N / 2] = even[k].sub(twiddle);
}
return output;
}
function fftFromRange(range) {
const input = range.flat().map(x => new Complex(Number(x), 0));
const N = input.length;
if ((N & (N - 1)) !== 0) throw new Error("Input length must be a power of 2");
const result = fft(input);
return result.map(c => [c.re, c.im]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment