Sunday June 12, 2005
Printing C language Complex and Imaginary numbers
_Complex & _Imaginary in the
absense of <complex.h>.
_Complex types have the same alignment and size of a two element array of the corresonding real type.
_Imaginary types have the same alignment and size of the corresponding real type.
_Complex and
_Imaginary numbers. However new functions
cimag() and creal() are available in
<complex.h> to retreive the real and imaginary
parts as their corresponding real floating point types. Note you cannot
pass an _Imaginary= number to %f because
_Imaginary will not be promoted to the double that
%f expects. You must spoof the type via a pointer.
Below is a non-portable way to print _Complex &
_Imaginary in the absense of <complex.h>.
% more t.c
#include <stdio.h>
#define str(s) #s
#define xstr(s) str(s)
#define T float
#define CRe(T, z) ((T *) &z)[0]
#define CIm(T, z) ((T *) &z)[1]
#define Im(T, z) ((T *) &z)[0]
int
main(void) {
T _Complex a = 3.0F + 4.0F * _Imaginary_I;
T _Imaginary b = a;
T g;
g = (T) a;
(void) printf("g=(" xstr(T) ")(%f, %f)=%f \n",
CRe(T, a), CIm(T, a), g);
(void) printf("_Imaginary b = (%f)\n", Im(T, b));
return(0);
}
% cc t.c
% a.out
g=(float)(3.000000, 4.000000)=3.000000
_Imaginary b = (4.000000)
%
( Jun 12 2005, 08:24:41 PM PDT )
Permalink
Comments [0]