Apache Commons Math3學習筆記(1)- 快速傅立葉變換

傅立葉變換:org.apache.commons.math3.transform.FastFourierTransformer類。

用法示例代碼:

double  inputData = new double[arrayLength];

// ... 給inputData賦值

FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
Complex[] result = fft.transform(inputData, TransformType.FORWARD);

使用還是非常簡單的。首先要創建待計算數據的數組,可以是double類型,亦可是org.apache.commons.math3.complex.Complex類型,然後創建org.apache.commons.math3.transform.FastFourierTransformer對象實例,最後調用其transform方法即可得到存放於複數數組中的傅立葉變換結果。

完整的示例代碼如下:

import org.apache.commons.math3.transform.DftNormalization;
import org.apache.commons.math3.transform.FastFourierTransformer;
import org.apache.commons.math3.transform.TransformType;

interface TestCase
{
   public Object run(List<Object> params) throws Exception;
   public List<Object> getParams();
}

class CalcFFT implements TestCase
{
   public CalcFFT()
   {
      System.out.print("本算例用於計算快速傅立葉變換。正在初始化 計算數據(" + arrayLength + "點)... ...");
      inputData = new double[arrayLength];
      for (int index = 0; index < inputData.length; index++)
      {
         inputData[index] = (Math.random() - 0.5) * 100.0;
      }
      System.out.println("初始化完成");
   }

   @Override
   public List<Object> getParams()
   {
      return null;
   }

   @Override
   public Object run(List<Object> params) throws Exception
   {
      FastFourierTransformer fft = new FastFourierTransformer(DftNormalization.STANDARD);
      Complex[] result = fft.transform(inputData, TransformType.FORWARD);
      return result;
   }

   private double[] inputData = null;
   private final int arrayLength = 4 * 1024*1024;

}

public class TimeCostCalculator
{
   public TimeCostCalculator()
   {
   }

   /**
    * 計算指定對象的運行時間開銷。
    * 
    * @param testCase 指定被測對象。
    * @return 返回sub.run的時間開銷,單位爲s。
    * @throws Exception
    */
   public double calcTimeCost(TestCase testCase) throws Exception
   {
      List<Object> params = testCase.getParams();
      long startTime = System.nanoTime();
      testCase.run(params);
      long stopTime = System.nanoTime();
      System.out.println("start: " + startTime + " / stop: " + stopTime);
      double timeCost = (stopTime - startTime) * 1.0e-9;
      //      double timeCost = BigDecimal.valueOf(stopTime - startTime, 9).doubleValue();
      return timeCost;
   }

   public static void main(String[] args) throws Exception
   {
      TimeCostCalculator tcc = new TimeCostCalculator();
      double timeCost;

      System.out.println("--------------------------------------------------------------------------");
      timeCost = tcc.calcTimeCost(new CalcFFT());
      System.out.println("time cost is: " + timeCost + "s");
      System.out.println("--------------------------------------------------------------------------");
   }

}
在i5四核處理器+16GB內存的臺式機上,計算4百萬點FFT,耗時0.7s。還是挺快的。

發佈了54 篇原創文章 · 獲贊 10 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章