C++ complex imag

The C++ complex imag function compute the imaginary value of the complex number as a real part. There are three overloaded versions of ‘imag’ functions. The declaration of the three functions is shown below.

1 constexpr T imag( ) const;
2 void imag(T val);
3 template<class T> constexpr T imag(const complex< T >& x);

The first two are member functions of the complex calss, but the third one is non-member function.A detail description of each of this function is given below.

Link : C++ complex real function


constexpr T imag( ) const;

This function returns the imaginary value as a real number of the complex number.

Parameters:
none

Return type
T -The imaginary value of the complex number.

complex< double > c1(232.4 , 99.34);

cout<< c1.imag() << endl ;

complex< int > cI(500 , 900);

cout<< cI.imag() << endl ;

Output,

99.34
900

The output values are the imaginary values of c1 and CI.

Note, if we assign the returned value of imag() function to a complex number then the returned value is not assigned to the imaginary part of the complex number. The imag() returned value is assigned to the real part of the left side complex number and the imaginary part is assigned 0.

complex< double > c1(9.56 , 99) , c2( 129, 90320 );
c2=c1.imag() ;

cout<< c2.real() ; << endl //Accessing the real part of c2
 << c2.imag() ;

Output

90320
0

You can see that the imaginary value of c1 is assigned to the real part of c2, moreover the imaginary part of c2 is overwritten by the value 0.



void imag(T val);

The sole purpose of this function is to change the imaginary part of the complex number.

Parameters:
val :Teh value to be newly assigned to the imaginary part of the complex number.

Return type
none

complex< double > c1(4.56 , 9.999 );
c1.imag( 6666 );

cout<< c1.imag() ;

Output,

6666


template<class T> complex< T > imag(const complex< T >& x);

This functions also returns the imaginary part of the complex number as a real.This function is similar in all ways to the first ‘imag’ function except it is non-member function.

Parameters:
Complex number -A complex number whose imaginary value is to be accessed.
 
Return type
template<class T> -The returned value is either ‘x.imag()’, or a complex number of the form (x.imag() , 0) if assigned to a complex object. Note the imaginary part is always 0.

complex<long double > c1(11.2 , 0.54) , c2(19.0 , 0.004) ;
cout<< imag( c1 ) << endl ;

c2=c1.imag( );

cout<< c2.real( ) << endl
 << c2.imag( ) ; //access the imaginary value of c2

Output ,

0.54
0.54
0

c2 initial real value is 19.0, but after the line ‘c2=imag( c1 ) ;’ the real value of c2 is assigned the 0.54(the imaginary value of c1) and the imaginary part of c2 is overwritten by the value 0.




Leave a Reply

Your email address will not be published. Required fields are marked *