next up previous
Next: Variable size multi-dimensional arrays Up: Scientific programming in C Previous: C++ extensions to C

Complex numbers

As we have already mentioned, the C language definition does not include complex arithmetic--presumably because the square root of minus one is not a concept which crops up very often in systems programming! Fortunately, this rather serious deficiency--at least, as far as the scientific programmer is concerned--is remedied in C++. The program listed below illustrates the use of the C++ complex class (header file complex.h) to perform complex arithmetic using doubles:
/* complex.cpp */
/*
  Program to test out C++ complex class 
*/

#include <complex.h>
#include <stdio.h>

/* Define complex double data type */
typedef complex<double> dcomp; 

int main()
{
  dcomp i, a, b, c, d, e, p, q, r; // Declare complex double variables
  double x, y;

  /* Set complex double variable equal to complex double constant */
  i = dcomp (0., 1.); 
  printf("\ni = (%6.4f, %6.4f)\n", i);

  /* Test arithmetic operations with complex double variables */
  a = i * i;
  b = 1. / i;  
  printf("\ni*i = (%6.4f, %6.4f)\n", a);
  printf("1/i = (%6.4f, %6.4f)\n", b);

  /* Test mathematical functions using complex double variables */
  c = sqrt(i);
  d = sin(i);
  e = pow(i, 0.25); 
  printf("\nsqrt(i) = (%6.4f, %6.4f)\n", c);
  printf("sin(i) = (%6.4f, %6.4f)\n", d);
  printf("i^0.25 = (%6.4f, %6.4f)\n", e);

  /* Test complex operations */
  p = conj(i);
  q = real(i);
  r = imag(i);
  printf("\nconj(i) = (%6.4f, %6.4f)\n", p);
  printf("real(i) = %6.4f\n", q);
  printf("imag(i) = %6.4f\n", r);

  return 0;
}
The typical output from this program is as follows:
 
i = (0.0000, 1.0000)
 
i*i = (-1.0000, 0.0000)
1/i = (0.0000, -1.0000)
 
sqrt(i) = (0.7071, 0.7071)
sin(i) = (0.0000, 1.1752)
i^0.25 = (0.9239, 0.3827)
 
conj(i) = (0.0000, -1.0000)
real(i) = 0.0000
imag(i) = 1.0000
%                              
The program first of all defines the complex double type dcomp. Variables of this type are then declared, set equal to complex constants, employed in arithmetic expressions, used as the arguments of mathematical functions, etc., in much the same manner that we would perform similar operations in C with variables of type double. Note the special functions conj(), real(), and imag(), which take the complex conjugate of, find the real part of, and find the imaginary part of a complex variable, respectively.


next up previous
Next: Variable size multi-dimensional arrays Up: Scientific programming in C Previous: C++ extensions to C
Richard Fitzpatrick 2006-03-29