Skip to content

implements InverseReal #74

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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