Skip to content

Commit

Permalink
Merge branch 'main' into hamming_hanning_periodic
Browse files Browse the repository at this point in the history
  • Loading branch information
swharden authored Aug 21, 2023
2 parents c92f3f6 + 68b9545 commit c555783
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
19 changes: 19 additions & 0 deletions src/FftSharp.Tests/Inverse.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,24 @@ public void Test_IFFT_MatchesOriginal()
Assert.AreEqual(original[i].Imaginary, ifft[i].Imaginary, 1e-6);
}
}

[Test]
public void Test_InverseReal_MatchesOriginal()
{
Random rand = new Random(0);
double[] original = new double[1024];
for (int i = 0; i < original.Length; i++)
original[i] = rand.NextDouble() - .5;

System.Numerics.Complex[] rfft = FftSharp.FFT.ForwardReal(original);
double[] irfft = FftSharp.FFT.InverseReal(rfft);

Assert.AreEqual(original.Length, irfft.Length);

for (int i = 0; i < irfft.Length; i++)
{
Assert.AreEqual(original[i], irfft[i], 1e-10);
}
}
}
}
33 changes: 32 additions & 1 deletion src/FftSharp/FFT.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using System;
using System;

namespace FftSharp;

Expand Down Expand Up @@ -73,6 +73,37 @@ public static System.Numerics.Complex[] ForwardReal(double[] samples)
return real;
}

/// <summary>
/// Calculate IFFT and return just the real component of the spectrum
/// </summary>
public static double[] InverseReal(System.Numerics.Complex[] spectrum)
{
int spectrumSize = spectrum.Length;
int windowSize = (spectrumSize - 1) * 2;

if (!FftOperations.IsPowerOfTwo(windowSize))
throw new ArgumentException($"{nameof(spectrum)} length must be a power of two plus 1");

System.Numerics.Complex[] buffer = new System.Numerics.Complex[windowSize];

for (int i = 0; i < spectrumSize; i++)
buffer[i] = spectrum[i];

for (int i = spectrumSize; i < windowSize; i++)
{
int iMirrored = spectrumSize - (i - (spectrumSize - 2));
buffer[i] = System.Numerics.Complex.Conjugate(spectrum[iMirrored]);
}

Inverse(buffer);

double[] result = new double[windowSize];
for (int i = 0; i < windowSize; i++)
result[i] = buffer[i].Real;

return result;
}

/// <summary>
/// Apply the inverse Fast Fourier Transform (iFFT) to the Complex array in place.
/// Length of the array must be a power of 2.
Expand Down

0 comments on commit c555783

Please sign in to comment.