当前位置:首页 > JavaScript

js实现FFT

2026-03-15 02:16:00JavaScript

FFT 算法实现

快速傅里叶变换(FFT)是一种高效计算离散傅里叶变换(DFT)的算法。以下是使用 JavaScript 实现 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:

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

性能优化

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

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

应用示例

计算信号的幅度谱:

js实现FFT

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

注意事项

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

标签: jsFFT
分享给朋友:

相关文章

js实现论坛

js实现论坛

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

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

js实现投球

js实现投球

实现投球动画的基本思路 使用JavaScript和CSS动画结合的方式模拟投球效果。核心是通过改变元素的位置、旋转和缩放属性,配合定时器或CSS过渡实现平滑动画。 创建基础HTML结构 <…

js实现上传文件

js实现上传文件

文件上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。 <input type="file"…

js实现 拖动

js实现 拖动

实现拖动的步骤 HTML 结构 创建一个可拖动的元素和一个放置区域: <div id="draggable" draggable="true">拖动我</div> <d…