single out the parts of a complex data type


stvurkel
03-22-2009, 10:29 PM
Hello everyone,
I have a little problem in NR, may be you have some idea about it.
When we define a complex-valued vector using
Vect_CPLX_DP, the vector elements will have real and imaginary parts.
The problem is, how to pick the real part only or imaginary part only of this complex
vector element and assign it to a variable, if I insist on using complex vector, not
separating it out into two real parts (representing real and imaginary) in the first
place.
I use NR 2nd edition with C++ by the way.

Thanks in advance.

davekw7x
03-27-2009, 10:21 AM
...how to pick the real part only or imaginary part only of this complex vector element and assign it to a variable, ...
Vec_CPLX_DP is a template class that uses the C++ Standard Template Library complex data type, so you can use the <complex> member functions real() and imag() to access the components:

//
// Illustration of access to Vec_CPLX_CP component parts
//
// davekw7x
//
#include "nrtypes.h"

int main()
{
Vec_CPLX_DP vz(10); // NRVec of 10 complex doubles

complex<DP> z0(1.0,2.0);
complex<DP> z1(3.0,4.0);
complex<DP> z2;

DP x0, y0, x1, y1, x2, y2;

vz[0] = z0;
vz[1] = z1;
vz[2] = vz[0]+vz[1];
z2 = vz[2];
//
// Note that STL complex class has an overloaded "<<" operator:
//
cout << "z0 = " << z0 << endl;
cout << "z1 = " << z1 << endl;
cout << "z2 = " << z2 << endl << endl;

x0 = vz[0].real();
y0 = vz[0].imag();
x1 = vz[1].real();
y1 = vz[1].imag();
x2 = vz[2].real();
y2 = vz[2].imag();

cout << "vz[0] = (" << x0 << "," << y0 << ")" << endl;
cout << "vz[1] = (" << x1 << "," << y1 << ")" << endl;
cout << "vz[2] = (" << x2 << "," << y2 << ")" << endl;

return 0;
}


Output:

z0 = (1,2)
z1 = (3,4)
z2 = (4,6)

vz[0] = (1,2)
vz[1] = (3,4)
vz[2] = (4,6)


Regards,

Dave