mathnet-numerics icon indicating copy to clipboard operation
mathnet-numerics copied to clipboard

FFT results using MathNet 4.12 different from Python Numpy fft for signals with many (> 100000) samples

Open Butz83 opened this issue 4 years ago • 0 comments

I am trying to replicate the FFT analysis of a Python code in C# using MathNet.Numerics.Fourier.Forward of a Sin signal. Using a number of samples of 5x10^4 the resulting FFT is identical in both C# and Python. With a bigger number of samples (for example 5x10^5) I get different FFT results.

// C# code

  var fs = 5*Math.Pow(10, 5);       // Sampling frequency [Hz]
  var duration = 10;                // Duration of the test signal [s]
  var N = Convert.ToInt32(fs*duration);
  var t_ = new List<double>();
  var rValue = 0;
  while (rValue < N)
  {
      t_.Add(rValue);
      rValue = rValue + 1;
  }
  var t = t_.Select(d => d/fs).ToArray();
  var f = 1000;                     // Frequency of the test signal [Hz]
  var sensitivity = 0.004;           
  var amp = sensitivity*Math.Sqrt(2);  
  var signal = new double[t.Length];
  for (var i = 0; i < t.Length; i++)
    signal[i] = amp * Math.Sin(2 * Math.PI * f * duration * t[i]);  

  var win = MathNet.Numerics.Window.Hamming(N).Select(x => Math.Round(x, 2)).ToArray();
  var signal_new = new double[signal.Length];
  for(var i  = 0; i < signal_new.Length; i++)
    signal_new[i] =  signal[i]*win[i];

  var aDataComplex = signal_new.Select(d => new Complex32(Convert.ToSingle(d), 0)).ToArray();
  Fourier.Forward(aDataComplex, FourierOptions.Matlab);

// Python code

  import numpy as np
  
  fs = 5e5       # Sampling frequency [Hz]
  duration = 10  # Duration of the test signal [s]
  N = int(fs * duration)
  t = np.arange(N, dtype=float) / fs
  f = 1000  # Frequency of the test signal [Hz]
  sensitivity = 0.004  
  amp = sensitivity * np.sqrt(2)  
  signal = amp * np.sin(2 * np.pi * f * duration * t)  
  win = np.hamming(N)
  signal_n = signal * win
  RESULT = np.fft.fft(signal_n);

tempsnip

Butz83 avatar Nov 17 '20 12:11 Butz83