当前位置:首页 > JavaScript

js实现FFT

2026-03-15 02:16:00JavaScript

FFT 算法实现

快速傅里叶变换(FFT)是一种高效计算离散傅里叶变换(DFT)的算法。以下是使用 JavaScript 实现 FFT 的代码示例:

js实现FFT

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 === 1));

    const output = new Array(N);
    for (let k = 0; k < N / 2; k++) {
        const angle = -2 * Math.PI * k / N;
        const exp = new Complex(Math.cos(angle), Math.sin(angle)).multiply(odd[k]);

        output[k] = even[k].add(exp);
        output[k + N / 2] = even[k].subtract(exp);
    }
    return output;
}

class Complex {
    constructor(real, imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    add(other) {
        return new Complex(this.real + other.real, this.imaginary + other.imaginary);
    }

    subtract(other) {
        return new Complex(this.real - other.real, this.imaginary - other.imaginary);
    }

    multiply(other) {
        return new Complex(
            this.real * other.real - this.imaginary * other.imaginary,
            this.real * other.imaginary + this.imaginary * other.real
        );
    }
}

使用说明

输入数据应为复数数组,实部和虚部都需要提供。如果输入是实数信号,可以将虚部设为0:

js实现FFT

const realSignal = [1, 2, 3, 4];
const complexInput = realSignal.map(x => new Complex(x, 0));
const spectrum = fft(complexInput);

性能优化

对于实际应用,可以考虑以下优化措施:

  • 预计算旋转因子(twiddle factors)
  • 使用迭代而非递归实现
  • 采用位反转排列优化内存访问模式
  • 考虑使用WebAssembly或GPU加速计算密集型部分

应用示例

计算信号的幅度谱:

function magnitudeSpectrum(fftOutput) {
    return fftOutput.map(c => Math.sqrt(c.real * c.real + c.imaginary * c.imaginary));
}

注意事项

  • 输入长度应为2的幂次方,否则需要补零
  • 浮点数精度可能导致计算误差
  • 对于实时应用,需要考虑算法延迟和计算效率

标签: jsFFT
分享给朋友:

相关文章

js实现动画

js实现动画

使用 CSS 动画与 JavaScript 控制 通过 JavaScript 动态添加或移除 CSS 类来触发动画。CSS 定义关键帧(@keyframes),JavaScript 通过 classL…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现论坛

js实现论坛

实现论坛的基本功能 使用JavaScript实现一个论坛需要结合前端和后端技术。前端可以使用React、Vue或Angular等框架,后端可以选择Node.js配合Express或Koa框架。数据库可…

使用js实现

使用js实现

使用JavaScript实现 JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。 // 生成0到1之间的随机小数 const random…

js实现求导

js实现求导

实现数值求导的方法 在JavaScript中实现求导通常采用数值方法,因为JavaScript不是符号计算语言。以下是常见的数值微分方法: 中心差分法 中心差分法提供较高精度的导数近似:…