Java实现的傅里叶变化算法示例

本文实例讲述了Java实现的傅里叶变化算法。分享给大家供大家参考,具体如下:

用JAVA实现傅里叶变化 结果为复数形式 a+bi

废话不多说,实现代码如下,共两个class

FFT.class 傅里叶变化功能实现代码

package fft.test;
/*************************************************************************
 * 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
 *********************************************************************/

Complex.class 复数类

package fft.test;
/******************************************************************************
 * Compilation: javac Complex.java
 * Execution:  java Complex
 *
 * Data type for complex numbers.
 *
 * The data type is "immutable" so once you create and initialize
 * a Complex object, you cannot change it. The "final" keyword
 * when declaring re and im enforces this rule, making it a
 * compile-time error to change the .re or .im instance variables after
 * they've been initialized.
 *
 * % java Complex
 * a      = 5.0 + 6.0i
 * b      = -3.0 + 4.0i
 * Re(a)    = 5.0
 * Im(a)    = 6.0
 * b + a    = 2.0 + 10.0i
 * a - b    = 8.0 + 2.0i
 * a * b    = -39.0 + 2.0i
 * b * a    = -39.0 + 2.0i
 * a / b    = 0.36 - 1.52i
 * (a / b) * b = 5.0 + 6.0i
 * conj(a)   = 5.0 - 6.0i
 * |a|     = 7.810249675906654
 * tan(a)    = -6.685231390246571E-6 + 1.0000103108981198i
 *
 ******************************************************************************/
import java.util.Objects;
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);
  }
  // See Section 3.3.
  public int hashCode() {
    return Objects.hash(re, 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());
  }
}

更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

(0)

相关推荐

  • JAVA实现感知器算法

    简述 随着互联网的高速发展,A(AI)B(BigData)C(Cloud)已经成为当下的核心发展方向,假如三者深度结合的话,AI是其中最核心的部分.所以如果说在未来社会,每个人都必须要学会编程的话,那么对于程序员来说,人工智能则是他们所必须掌握的技术(科技发展真tm快). 这篇文章介绍并用JAVA实现了一种最简单的感知器网络,不纠结于公式的推导,旨在给大家提供一下学习神经网络的思路,对神经网络有一个大概的认识. 感知器网络模型分析 首先看一张图 如果稍微对神经网络感兴趣的一定对这张图不陌生,这张

  • 使用栈的迷宫算法java版代码

    本文为大家分享了使用栈的迷宫算法java版,主要考察栈的使用,供大家参考,具体内容如下 主要思路如下: do { if(当前位置可通过) { 标记此位置已走过; 保存当前位置并入栈; if(当前位置为终点) { 程序结束; } 获取下一个位置; } else { if(栈非空) { 出栈: while(当前位置方向为4且栈非空) { 标记当前位置不可走; 出栈; } if(当前位置的方向小于4) { 方向+1; 重新入栈; 获取下一个位置; } } } } while (栈非空); java代码

  • 以Python代码实例展示kNN算法的实际运用

    邻近算法,或者说K最近邻(kNN,k-NearestNeighbor)分类算法是数据挖掘分类技术中最简单的方法之一.所谓K最近邻,就是k个最近的邻居的意思,说的是每个样本都可以用它最接近的k个邻居来代表. kNN算法的核心思想是如果一个样本在特征空间中的k个最相邻的样本中的大多数属于某一个类别,则该样本也属于这个类别,并具有这个类别上样本的特性.该方法在确定分类决策上只依据最邻近的一个或者几个样本的类别来决定待分样本所属的类别. kNN方法在类别决策时,只与极少量的相邻样本有关.由于kNN方法主

  • Python实现的knn算法示例

    本文实例讲述了Python实现的knn算法.分享给大家供大家参考,具体如下: 代码参考机器学习实战那本书: 机器学习实战 (Peter Harrington著) 中文版 机器学习实战 (Peter Harrington著) 英文原版[附源代码] 有兴趣你们可以去了解下 具体代码: # -*- coding:utf-8 -*- #! python2 ''''' @author:zhoumeixu createdate:2015年8月27日 ''' #np.zeros((4,2)) #np.zero

  • Java实现Floyd算法求最短路径

    本文实例为大家分享了Java实现Floyd算法求最短路径的具体代码,供大家参考,具体内容如下 import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; public class TestMainIO { /** * @param args * @throws FileNotFoundException */ public static void main(Stri

  • kNN算法python实现和简单数字识别的方法

    本文实例讲述了kNN算法python实现和简单数字识别的方法.分享给大家供大家参考.具体如下: kNN算法算法优缺点: 优点:精度高.对异常值不敏感.无输入数据假定 缺点:时间复杂度和空间复杂度都很高 适用数据范围:数值型和标称型 算法的思路: KNN算法(全称K最近邻算法),算法的思想很简单,简单的说就是物以类聚,也就是说我们从一堆已知的训练集中找出k个与目标最靠近的,然后看他们中最多的分类是哪个,就以这个为依据分类. 函数解析: 库函数: tile() 如tile(A,n)就是将A重复n次

  • Java实现的KNN算法示例

    本文实例讲述了Java实现的KNN算法.分享给大家供大家参考,具体如下: 提起KNN算法大家应该都不会陌生,对于数据挖掘来说算是十大经典算法之一. 算法的思想是:对于训练数据集中已经归类的分组,来对于未知的数据进行分组归类.其中是根据该未知点与其训练数据中的点计算距离,求出距离最短的点,并将其归入该点的那一类. 看看算法的工程吧: 1. 准备数据,对数据进行预处理 2. 选用合适的数据结构存储训练数据和测试元组 3. 设定参数,如k 4.维护一个大小为k的的按距离由大到小的优先级队列,用于存储最

  • Java实现的朴素贝叶斯算法示例

    本文实例讲述了Java实现的朴素贝叶斯算法.分享给大家供大家参考,具体如下: 对于朴素贝叶斯算法相信做数据挖掘和推荐系统的小伙们都耳熟能详了,算法原理我就不啰嗦了.我主要想通过java代码实现朴素贝叶斯算法,思想: 1. 用javabean +Arraylist 对于训练数据存储 2. 对于样本数据训练 具体的代码如下: package NB; /** * 训练样本的属性 javaBean * */ public class JavaBean { int age; String income;

  • python使用KNN算法手写体识别

    本文实例为大家分享了用KNN算法手写体识别的具体代码,供大家参考,具体内容如下 #!/usr/bin/python #coding:utf-8 import numpy as np import operator import matplotlib import matplotlib.pyplot as plt import os ''''' KNN算法 1. 计算已知类别数据集中的每个点依次执行与当前点的距离. 2. 按照距离递增排序. 3. 选取与当前点距离最小的k个点 4. 确定前k个点所

  • Java实现走迷宫回溯算法

    以一个M×N的长方阵表示迷宫,0和1分别表示迷宫中的通路和障碍.设计一个程序,对任意设定的迷宫,求出一条从入口到出口的通路,或得出没有通路的结论. (1) 根据二维数组,输出迷宫的图形. (2) 探索迷宫的四个方向:RIGHT为向右,DOWN向下,LEFT向左,UP向上,输出从入口到出口的行走路径. 例子: 左上角(1,1)为入口,右下角(8,9)为出口. 可使用回溯方法,即从入口出发,顺着某一个方向进行探索,若能走通,则继续往前进:否则沿着原路退回,换一个方向继续探索,直至出口位置,求得一条通

  • Java实现五子棋AI算法

    五子棋AI算法 也算是一个典型的游戏AI算法,一些棋类的AI算法都可以参考实现,下面是Java实现代码 棋盘抽象接口 import java.util.List; public interface IChessboard { //取得棋盘最大横坐标 public int getMaxX(); //最大纵坐标 public int getMaxY(); //取得当前所有空白点,这些点才可以下棋 public List<Point> getFreePoints(); } 棋子类实现 //棋子类 p

随机推荐