Douglas Walls' Weblog

Main | c89 command on linux »
20050612 Sunday June 12, 2005

Printing C language Complex and Imaginary numbers

How to print Complex and Imaginary numbers

The 1999 C standard (C99), among many other changes, added support for Complex and Imaginary numbers. SunStudio 10 C 5.7 is fully compliant with the C99 standard on Solaris 10. SunStudio 10 is also supported on Solaris 8 and 9. However, Solaris 8 and 9 do not provide the header files neccessary for full C99 support. Below I describe a non-portable way to print _Complex & _Imaginary in the absense of <complex.h>.

There are no printf specifiers to print _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]

Trackback URL: http://blogs.sun.com/dew/entry/printing_c_language_complex_and
Comments:

Post a Comment:

Name:
E-Mail:
URL:

Your Comment:

HTML Syntax: NOT allowed

Search

Calendar

Links

Navigation

Referers