SourcePro : Essential Math Module User’s Guide : Examples : Example Using the FFT Server Class
Example Using the FFT Server Class
Example 3 – Using the FFT Server Class
FILENAME: example3.cpp
Program:
/*
* Example program using the Complex FFT server class.
*/
 
// Include the header file for complex FFT server class:
#include <rw/cfft.h>
// Header files for complex vectors:
#include <rw/math/mathvec.h>
#include <math.h>
#include <iostream>
 
int main()
{
// Set series length:
unsigned npts = 12;
// Allocate a server:
DComplexFFTServer server;
/*
* Create two series, one a cosine series, the
* other a sine series. This is done by first
* using a constructor for an RWMathVec<double> with
* increasing elements, taking the cosine (or
* sine) of this vector, then constructing a
* complex vector from that.
*/
// One cycle:
RWMathVec<DComplex> a =
cos( RWMathVec<double>(npts,0,2.0*M_PI/npts) );
// Two cycles:
RWMathVec<DComplex> a2 =
sin( RWMathVec<double>(npts,0,4.0*M_PI/npts) );
/*
* Calculate the superposition of the two. Note that we
* are adding two complex vectors here with one
* simple statement.
*/
 
RWMathVec<DComplex> asum = a + a2;
 
// Output the vectors:
std::cout << "a:\n" << a << "\n";
std::cout << "a2:\n" << a2 << "\n";
std::cout << "asum:\n" << asum << "\n";
 
/*
* Print out the transforms, normalized by the
* number of points.
*/
 
std::cout << "\nTransform of a:\n";
std::cout << server.fourier(a)/DComplex(npts);
 
std::cout << "\nTransform of a2:\n";
std::cout << server.fourier(a2)/DComplex(npts);
 
RWMathVec<DComplex> asumFFT = server.fourier(asum);
 
std::cout << "\nTransform of asum:\n";
std::cout << asumFFT/DComplex(npts);
 
/*
* Check Parseval's Theorem. First, calculate the
* variance of the series asum, using the global
* function variance().
*/
std::cout << "\nOriginal Variance: "
<< variance(asum) << "\n";
 
/*
* Next, calculate the spectral variance of the Fourier
* transformed series, using the global function
* spectralVariance().
*/
 
double var = spectralVariance(asumFFT/DComplex(npts));
 
std::cout << "Spectral Variance: " << var << "\n\n";
 
/*
* Print out the normalized back transform of
* asumFFT; this should equal the original asum.
*/
 
std::cout << "\nBack Transform of asum:\n"
<<server.ifourier(asumFFT)/DComplex(npts);
}
Sample Input:
None required.
Sample Output:
See file example3.out in the examples directory for the complete sample output. Note that the exact numbers depend on machine precision.
 
a:
[
( 1, 0) ( 0.866, 0) ( 0.5, 0) ( 0, 0) ...
]
 
a2:
[
( 0, 0) ( 0.866, 0) ( 0.866, 0) ( 0, 0) ...
]
 
asum:
[
( 1, 0) ( 1.732, 0) ( 1.366, 0) ( 0, 0) ...
]
 
Transform of a:
[
( 0, 0) ( 0.5, 0) ( 0, 0) ...
]
 
Transform of a2:
[
( 0, 0) ( 0, 0) ( 0, -0.5) ...
 
Transform of asum:
[
( 0, 0) ( 0.5, 0) ( 0, -0.5) ...
]
 
Original variance: 1
Spectral variance: 1
 
Back transform of asum:
[
( 1, 0) ( 1.732, 0) ( 1.366, 0) ( 0, 0) ...
]