java 实现傅立叶变换算法 及复数的运算
最近项目需求,需要把python中的算法移植到java上,其中有一部分需要用到复数的运算和傅立叶变换算法,废话不多说 如下:
package qrs;
/**
 *  复数的运算
 *
 */
public class Complex {
    private final double re; // the real part
    private final double im; // the imaginary part
    // create a new object with the given real and imaginary parts
    public Complex(double real, double imag) {
        re = real;
        im = imag;
    }
    // return a string representation of the invoking Complex object
    public String toString() {
        if (im == 0)
            return re + "";
        if (re == 0)
            return im + "i";
        if (im < 0)
            return re + " - " + (-im) + "i";
        return re + " + " + im + "i";
    }
    // return abs/modulus/magnitude
    public double abs() {
        return Math.hypot(re, im);
    }
    // return angle/phase/argument, normalized to be between -pi and pi
    public double phase() {
        return Math.atan2(im, re);
    }
    // return a new Complex object whose value is (this + b)
    public Complex plus(Complex b) {
        Complex a = this; // invoking object
        double real = a.re + b.re;
        double imag = a.im + b.im;
        return new Complex(real, imag);
    }
    // return a new Complex object whose value is (this - b)
    public Complex minus(Complex b) {
        Complex a = this;
        double real = a.re - b.re;
        double imag = a.im - b.im;
        return new Complex(real, imag);
    }
    // return a new Complex object whose value is (this * b)
    public Complex times(Complex b) {
        Complex a = this;
        double real = a.re * b.re - a.im * b.im;
        double imag = a.re * b.im + a.im * b.re;
        return new Complex(real, imag);
    }
    // return a new object whose value is (this * alpha)
    public Complex scale(double alpha) {
        return new Complex(alpha * re, alpha * im);
    }
    // return a new Complex object whose value is the conjugate of this
    public Complex conjugate() {
        return new Complex(re, -im);
    }
    // return a new Complex object whose value is the reciprocal of this
    public Complex reciprocal() {
        double scale = re * re + im * im;
        return new Complex(re / scale, -im / scale);
    }
    // return the real or imaginary part
    public double re() {
        return re;
    }
    public double im() {
        return im;
    }
    // return a / b
    public Complex divides(Complex b) {
        Complex a = this;
        return a.times(b.reciprocal());
    }
    // return a new Complex object whose value is the complex exponential of
    // this
    public Complex exp() {
        return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im));
    }
    // return a new Complex object whose value is the complex sine of this
    public Complex sin() {
        return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im));
    }
    // return a new Complex object whose value is the complex cosine of this
    public Complex cos() {
        return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im));
    }
    // return a new Complex object whose value is the complex tangent of this
    public Complex tan() {
        return sin().divides(cos());
    }
    // a static version of plus
    public static Complex plus(Complex a, Complex b) {
        double real = a.re + b.re;
        double imag = a.im + b.im;
        Complex sum = new Complex(real, imag);
        return sum;
    }
    // See Section 3.3.
    public boolean equals(Object x) {
        if (x == null)
            return false;
        if (this.getClass() != x.getClass())
            return false;
        Complex that = (Complex) x;
        return (this.re == that.re) && (this.im == that.im);
    }
    // sample client for testing
    public static void main(String[] args) {
        Complex a = new Complex(3.0, 4.0);
        Complex b = new Complex(-3.0, 4.0);
        System.out.println("a            = " + a);
        System.out.println("b            = " + b);
        System.out.println("Re(a)        = " + a.re());
        System.out.println("Im(a)        = " + a.im());
        System.out.println("b + a        = " + b.plus(a));
        System.out.println("a - b        = " + a.minus(b));
        System.out.println("a * b        = " + a.times(b));
        System.out.println("b * a        = " + b.times(a));
        System.out.println("a / b        = " + a.divides(b));
        System.out.println("(a / b) * b  = " + a.divides(b).times(b));
        System.out.println("conj(a)      = " + a.conjugate());
        System.out.println("|a|          = " + a.abs());
        System.out.println("tan(a)       = " + a.tan());
    }
}
傅立叶变换部分需要依赖复数类
package qrs;
/*************************************************************************
 * Compilation: javac FFT.java Execution: java FFT N Dependencies: Complex.java
 *
 * Compute the FFT and inverse FFT of a length N complex sequence. Bare bones
 * implementation that runs in O(N log N) time. Our goal is to optimize the
 * clarity of the code, rather than performance.
 *
 * Limitations ----------- - assumes N is a power of 2
 *
 * - not the most memory efficient algorithm (because it uses an object type for
 * representing complex numbers and because it re-allocates memory for the
 * subarray, instead of doing in-place or reusing a single temporary array)
 *
 *************************************************************************/
public class FFT {
    // compute the FFT of x[], assuming its length is a power of 2
    public static Complex[] fft(Complex[] x) {
        int N = x.length;
        // base case
        if (N == 1)
            return new Complex[] { x[0] };
        // radix 2 Cooley-Tukey FFT
        if (N % 2 != 0) {
            throw new RuntimeException("N is not a power of 2");
        }
        // fft of even terms
        Complex[] even = new Complex[N / 2];
        for (int k = 0; k < N / 2; k++) {
            even[k] = x[2 * k];
        }
        Complex[] q = fft(even);
        // fft of odd terms
        Complex[] odd = even; // reuse the array
        for (int k = 0; k < N / 2; k++) {
            odd[k] = x[2 * k + 1];
        }
        Complex[] r = fft(odd);
        // combine
        Complex[] y = new Complex[N];
        for (int k = 0; k < N / 2; k++) {
            double kth = -2 * k * Math.PI / N;
            Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
            y[k] = q[k].plus(wk.times(r[k]));
            y[k + N / 2] = q[k].minus(wk.times(r[k]));
        }
        return y;
    }
    // compute the inverse FFT of x[], assuming its length is a power of 2
    public static Complex[] ifft(Complex[] x) {
        int N = x.length;
        Complex[] y = new Complex[N];
        // take conjugate
        for (int i = 0; i < N; i++) {
            y[i] = x[i].conjugate();
        }
        // compute forward FFT
        y = fft(y);
        // take conjugate again
        for (int i = 0; i < N; i++) {
            y[i] = y[i].conjugate();
        }
        // divide by N
        for (int i = 0; i < N; i++) {
            y[i] = y[i].scale(1.0 / N);
        }
        return y;
    }
    // compute the circular convolution of x and y
    public static Complex[] cconvolve(Complex[] x, Complex[] y) {
        // should probably pad x and y with 0s so that they have same length
        // and are powers of 2
        if (x.length != y.length) {
            throw new RuntimeException("Dimensions don't agree");
        }
        int N = x.length;
        // compute FFT of each sequence,求值
        Complex[] a = fft(x);
        Complex[] b = fft(y);
        // point-wise multiply,点值乘法
        Complex[] c = new Complex[N];
        for (int i = 0; i < N; i++) {
            c[i] = a[i].times(b[i]);
        }
        // compute inverse FFT,插值
        return ifft(c);
    }
    // compute the linear convolution of x and y
    public static Complex[] convolve(Complex[] x, Complex[] y) {
        Complex ZERO = new Complex(0, 0);
        Complex[] a = new Complex[2 * x.length];// 2n次数界,高阶系数为0.
        for (int i = 0; i < x.length; i++)
            a[i] = x[i];
        for (int i = x.length; i < 2 * x.length; i++)
            a[i] = ZERO;
        Complex[] b = new Complex[2 * y.length];
        for (int i = 0; i < y.length; i++)
            b[i] = y[i];
        for (int i = y.length; i < 2 * y.length; i++)
            b[i] = ZERO;
        return cconvolve(a, b);
    }
    // display an array of Complex numbers to standard output
    public static void show(Complex[] x, String title) {
        System.out.println(title);
        System.out.println("-------------------");
        int complexLength = x.length;
        for (int i = 0; i < complexLength; i++) {
            // 输出复数
            // System.out.println(x[i]);
            // 输出幅值需要 * 2 / length
            System.out.println(x[i].abs() * 2 / complexLength);
        }
        System.out.println();
    }
/**
     * 将数组数据重组成2的幂次方输出
     *
     * @param data
     * @return
     */
    public static Double[] pow2DoubleArr(Double[] data) {
        // 创建新数组
        Double[] newData = null;
        int dataLength = data.length;
        int sumNum = 2;
        while (sumNum < dataLength) {
            sumNum = sumNum * 2;
        }
        int addLength = sumNum - dataLength;
        if (addLength != 0) {
            newData = new Double[sumNum];
            System.arraycopy(data, 0, newData, 0, dataLength);
            for (int i = dataLength; i < sumNum; i++) {
                newData[i] = 0d;
            }
        } else {
            newData = data;
        }
        return newData;
    }
    /**
     * 去偏移量
     *
     * @param originalArr
     *            原数组
     * @return 目标数组
     */
    public static Double[] deskew(Double[] originalArr) {
        // 过滤不正确的参数
        if (originalArr == null || originalArr.length <= 0) {
            return null;
        }
        // 定义目标数组
        Double[] resArr = new Double[originalArr.length];
        // 求数组总和
        Double sum = 0D;
        for (int i = 0; i < originalArr.length; i++) {
            sum += originalArr[i];
        }
        // 求数组平均值
        Double aver = sum / originalArr.length;
        // 去除偏移值
        for (int i = 0; i < originalArr.length; i++) {
            resArr[i] = originalArr[i] - aver;
        }
        return resArr;
    }
    public static void main(String[] args) {
        // int N = Integer.parseInt(args[0]);
        Double[] data = { -0.35668879080953375, -0.6118094913035987, 0.8534269560320435, -0.6699697478438837, 0.35425500561437717,
                0.8910250650549392, -0.025718699518642918, 0.07649691490732002 };
        // 去除偏移量
        data = deskew(data);
        // 个数为2的幂次方
        data = pow2DoubleArr(data);
        int N = data.length;
        System.out.println(N + "数组N中数量....");
        Complex[] x = new Complex[N];
        // original data
        for (int i = 0; i < N; i++) {
            // x[i] = new Complex(i, 0);
            // x[i] = new Complex(-2 * Math.random() + 1, 0);
            x[i] = new Complex(data[i], 0);
        }
        show(x, "x");
        // FFT of original data
        Complex[] y = fft(x);
        show(y, "y = fft(x)");
        // take inverse FFT
        Complex[] z = ifft(y);
        show(z, "z = ifft(y)");
        // circular convolution of x with itself
        Complex[] c = cconvolve(x, x);
        show(c, "c = cconvolve(x, x)");
        // linear convolution of x with itself
        Complex[] d = convolve(x, x);
        show(d, "d = convolve(x, x)");
    }
}
/*********************************************************************
 * % java FFT 8 x ------------------- -0.35668879080953375 -0.6118094913035987
 * 0.8534269560320435 -0.6699697478438837 0.35425500561437717 0.8910250650549392
 * -0.025718699518642918 0.07649691490732002
 *
 * y = fft(x) ------------------- 0.5110172121330208 -1.245776663065442 +
 * 0.7113504894129803i -0.8301420417085572 - 0.8726884066879042i
 * -0.17611092978238008 + 2.4696418005143532i 1.1395317305034673
 * -0.17611092978237974 - 2.4696418005143532i -0.8301420417085572 +
 * 0.8726884066879042i -1.2457766630654419 - 0.7113504894129803i
 *
 * z = ifft(y) ------------------- -0.35668879080953375 -0.6118094913035987 +
 * 4.2151962932466006E-17i 0.8534269560320435 - 2.691607282636124E-17i
 * -0.6699697478438837 + 4.1114763914420734E-17i 0.35425500561437717
 * 0.8910250650549392 - 6.887033953004965E-17i -0.025718699518642918 +
 * 2.691607282636124E-17i 0.07649691490732002 - 1.4396387316837096E-17i
 *
 * c = cconvolve(x, x) ------------------- -1.0786973139009466 -
 * 2.636779683484747E-16i 1.2327819138980782 + 2.2180047699856214E-17i
 * 0.4386976685553382 - 1.3815636262919812E-17i -0.5579612069781844 +
 * 1.9986455722517509E-16i 1.432390480003344 + 2.636779683484747E-16i
 * -2.2165857430333684 + 2.2180047699856214E-17i -0.01255525669751989 +
 * 1.3815636262919812E-17i 1.0230680492494633 - 2.4422465262488753E-16i
 *
 * d = convolve(x, x) ------------------- 0.12722689348916738 +
 * 3.469446951953614E-17i 0.43645117531775324 - 2.78776395788635E-18i
 * -0.2345048043334932 - 6.907818131459906E-18i -0.5663280251946803 +
 * 5.829891518914417E-17i 1.2954076913348198 + 1.518836016779236E-16i
 * -2.212650940696159 + 1.1090023849928107E-17i -0.018407034687857718 -
 * 1.1306778366296569E-17i 1.023068049249463 - 9.435675069681485E-17i
 * -1.205924207390114 - 2.983724378680108E-16i 0.796330738580325 +
 * 2.4967811657742562E-17i 0.6732024728888314 - 6.907818131459906E-18i
 * 0.00836681821649593 + 1.4156564203603091E-16i 0.1369827886685242 +
 * 1.1179436667055108E-16i -0.00393480233720922 + 1.1090023849928107E-17i
 * 0.005851777990337828 + 2.512241462921638E-17i 1.1102230246251565E-16 -
 * 1.4986790192807268E-16i
 *********************************************************************/
java 实现傅立叶变换算法 及复数的运算的更多相关文章
- Java实现 蓝桥杯 算法提高 复数四则运算
		算法提高 6-17复数四则运算 时间限制:1.0s 内存限制:512.0MB 提交此题 设计复数库,实现基本的复数加减乘除运算. 输入时只需分别键入实部和虚部,以空格分割,两个复数之间用运算符分隔:输 ... 
- 为什么要进行傅立叶变换?傅立叶变换究竟有何意义?如何用Matlab实现快速傅立叶变换
		写在最前面:本文是我阅读了多篇相关文章后对它们进行分析重组整合而得,绝大部分内容非我所原创.在此向多位原创作者致敬!!!一.傅立叶变换的由来关于傅立叶变换,无论是书本还是在网上可以很容易找到关于傅立叶 ... 
- 傅立叶变换—DFT
		背景:最近看到实验室其他同学在用傅立叶变换解决问题,我也想通过并行来解决这个问题,所以看了一下傅立叶变换的东西,感觉涵盖的东西还能多,我只是初步做了一下了解(一定很片面,但是我主要是为了应用它,主要了 ... 
- 快速傅立叶变换(FFT)算法
		已知多项式f(x)=a0+a1x+a2x2+...+am-1xm-1, g(x)=b0+b1x+b2x2+...+bn-1xn-1.利用卷积的蛮力算法,得到h(x)=f(x)g(x),这一过程的时间复 ... 
- Java蓝桥杯 算法训练 复数归一化
		算法提高 复数归一化 时间限制:1.0s 内存限制:512.0MB 编写函数Normalize,将复数归一化,即若复数为a+bi,归一化结果为a/sqrt(aa+bb) + ib/sqrt(aa+b* ... 
- Java实现 蓝桥杯VIP 算法提高 复数求和
		算法提高 复数求和 时间限制:1.0s 内存限制:512.0MB 从键盘读入n个复数(实部和虚部都为整数)用链表存储,遍历链表求出n个复数的和并输出. 样例输入: 3 3 4 5 2 1 3 样例输出 ... 
- Matlab图像处理系列4———傅立叶变换和反变换的图像
		注意:这一系列实验的图像处理程序,使用Matlab实现最重要的图像处理算法 1.Fourier兑换 (1)频域增强 除了在空间域内能够加工处理图像以外,我们还能够将图像变换到其它空间后进行处理.这些方 ... 
- $\mathcal{FFT}$·$\mathcal{Fast \ \  Fourier  \ \ Transformation}$快速傅立叶变换
		\(2019.2.18upd:\) \(LINK\) 之前写的比较适合未接触FFT的人阅读--但是有几个地方出了错,大家可以找一下233 啊-本来觉得这是个比较良心的算法没想到这么抽搐这个算法真是将一 ... 
- Matlab图像处理系列4———图像傅立叶变换与反变换
		注:本系列来自于图像处理课程实验.用Matlab实现最主要的图像处理算法 1.Fourier变换 (1)频域增强 除了在空间域内能够加工处理图像以外.我们还能够将图像变换到其它空间后进行处理.这些方法 ... 
随机推荐
- Understand RNN with TensorFlow in 7 Steps
			待翻译 https://medium.com/@erikhallstrm/hello-world-rnn-83cd7105b767 
- EDA cheat sheet
			%config InlineBackend.figure_format = 'svg' 在jupyter notebook中使用这个命令绘制更清晰的图像,注意百分号后不能有空格. 1. Univari ... 
- Java常考面试题整理(三)
			明天又要去面试,Good luck to me.,让我在这段时间换个新的工作吧. 41.在Java中,对象什么时候可以被垃圾回收? 参考答案: 当对象对当前使用这个对象的应用程序变得不可触及的时候,这 ... 
- Javascript事件:this.value()和this.select()
			1.JavaScript的this.value() <asp:TextBox ID="txtComment" runat="server" Text=&q ... 
- Java期末课程学习汇总。
			本学期面向对象与Java程序设计课程已经结束了,给自己学习来个总结. 本学期过的非常快,不得不说这一学期学到的东西很少,感觉自己的进步很小. 而且感觉自己总少了点什么,在写这篇总结前,我认真想了,很多 ... 
- spark 笔记 13: 再看DAGScheduler,stage状态更新流程
			当某个task完成后,某个shuffle Stage X可能已完成,那么就可能会一些仅依赖Stage X的Stage现在可以执行了,所以要有响应task完成的状态更新流程. ============= ... 
- sqlserver2012语法
			1.SQL Server 2012 Format()方法 SQL Server 从 2012 开始增加了Format方法,可以使用 Format来格式化日期与数字,而且和 C# 里的日期格式化一致,语 ... 
- Mysql 基础操作命令
			1,查看mysql的建表语句 show create table tableName; #tableName 库中已存在的表名 
- Java-Logger日志
			<转载于--https://www.cnblogs.com/yorickLi/p/6158405.html> Java中关于日志系统的API,在 java.util.logging 包中, ... 
- SAE Django如何禁止外部IP访问
			在SAE上基于Django搭建的Web工程有时需要禁止来自某些特定IP地址的访问请求. 例如一个为搭建在SAE的其他项目提供服务的内部工程,可以设置为只允许SAE内部的IP地址访问,从而提高项目的安全 ... 
