Complex arithmetic

IMPLEMENTATION
A complex number is a string containing a real and an imaginary part separated by one or more blanks. The COMPLEX function creates a complex number from the real and imaginary parts.
 


COMPLEX: procedure
parse arg Re, Im; return Re Im

The REAL function returns the real part and the IMAGINARY function returns the imaginary part of a complex number.
 


REAL: procedure
parse arg Re Im; return Re
 
IMAGINARY: procedure
parse arg Re Im; return Im

 

ADDITION & SUBTRACTION
 


CADD: procedure
parse arg Ca, Cb
parse var Ca Ar Ai; parse var Cb Br Bi
return (Ar + Br) (Ai + Bi)

 


CSUB: procedure
parse arg Ca, Cb
parse var Ca Ar Ai; parse var Cb Br Bi
return (Ar - Br) (Ai - Bi)

 

MULTIPLICATION
 


CMUL: procedure
parse arg Ca, Cb
parse var Ca Ar Ai; parse var Cb Br Bi
return (Ar * Br - Ai * Bi),
  (Ai * Br + Ar * Bi)

 

DIVISION
 


CDIV: procedure
parse arg Ca, Cb
parse var Ca Ar Ai; parse var Cb Br Bi
if ABS(Br) >= ABS(Bi)
  then do
    R = Bi / Br
    Den = Br + R * Bi
    return,
      (Ar + R * Ai)/Den (Ai - R * Ar)/Den
  end
  else do
    R = Br / Bi
    Den = Bi + R * Br
    return,
      (Ar * R + Ai)/Den (Ai * R - Ar)/Den
  end

 

MODULUS
 


CABS: procedure
parse arg Ar Ai
X = ABS(Ar); Y = ABS(Ai)
select
  when X = 0 then return Y
  when Y = 0 then return X
  when X > Y
    then do
      W = Y/X
      return X * SQRT(1 + W * W)
    end
  otherwise
    W = X/Y
    return Y * SQRT(1 + W * W)
end

 

SQUARE ROOT
 


CSQRT: procedure
parse arg Ar Ai
if Ar = 0 & Ai = 0 then return 0 0
X = ABS(Ar); Y = ABS(Ai)
if X >= Y
  then do
    R = Y/X
    W = SQRT(X) *,
      SQRT(0.5 * (1 + SQRT(1 + R)))
  end
  else do
    R = X/Y
    W = SQRT(Y) *,
      SQRT(0.5 * (R + SQRT(1 + R)))
  end
if Ar >= 0 then return W (Ai / (2 * W))
  else do
    if Ai >= 0 then return Ai / (2 * W)
      else return Ai / (2 * -W)
  end

 

REAL MULTIPLIER
 


RCMUL: procedure
parse arg C, R
parse var C Ar Ai
return R * Ar R * Ai

 

EXAMPLE
The program


C1 = COMPLEX(1, 2)
C2 = COMPLEX(2, -1)
C3 = COMPLEX(0, 3)
say "C1 + C2 =" CADD(C1, C2)
say "C1 - C2 =" CSUB(C1, C2)
say "C1 * C2 =" CMUL(C1, C2)
say "C1 / C2 =" CDIV(C1, C2)
/*   |C1| = SQRT(5)               */
say "|C1| =" CABS(C1)
/* SQRT(C3) = SQRT(3/2) SQRT(3/2) */
say "SQRT(C3) =" CSQRT(C3)
exit
...

displays on the screen:


C1 + C2 = 3 1
C1 - C2 = -1 3
C1 * C2 = 4 3
C1 / C2 = 0 1
|C1| = 2.23606798
SQRT(C3) = 1.22474487 1.22474487

 

CONNECTIONS

Literature
Press W.H., Teukolsky S.A., Vetterling W.T., Flannery B.P., Numerical Recipes in C : the art of scientific computing
- 2nd ed. University Press, Cambridge, 1992


Cover Contents Index Main page Rexx page   Mail

last modified 8th August 2001
Copyright © 2000-2001 Vladimir Zabrodsky
Czech Republic
 

1