Arithmetic/Complex: Difference between revisions

From Rosetta Code
Content added Content deleted
(adding maxima)
m (→‎{{header|REXX}}: added whitespace, added a comment. -- ~~~~)
Line 2,487: Line 2,487:
cnjX = Ccnj(x); say ' conjugate of: ' x " = " cnjX
cnjX = Ccnj(x); say ' conjugate of: ' x " = " cnjX
negX = Cneg(x); say ' negation of: ' x " = " negX
negX = Cneg(x); say ' negation of: ' x " = " negX
exit /*stick a fork in it, we're done.*/
exit

/*─────────────────────────────────────one─liners───────────────────────*/
/*─────────────────────────────────────one─liners───────────────────────*/
Ccnj: procedure;arg a ',' b,c ',' d;call Cg;r1=a;r2=-b;return Cr()
Ccnj: procedure;arg a ',' b,c ',' d;call Cg;r1=a;r2=-b;return Cr()

Revision as of 19:06, 27 August 2012

Task
Arithmetic/Complex
You are encouraged to solve this task according to the task description, using any language you may know.

A complex number is a number which can be written as "" (sometimes shown as "") where a and b are real numbers and is the square root of -1. Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by .

  • Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested.
  • Optional: Show complex conjugation. By definition, the complex conjugate of is .

Some languages have complex number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type.

Ada

<lang ada>with Ada.Numerics.Generic_Complex_Types; with Ada.Text_IO.Complex_IO;

procedure Complex_Operations is

  -- Ada provides a pre-defined generic package for complex types
  -- That package contains definitions for composition,
  -- negation, addition, subtraction, multiplication, division,
  -- conjugation, exponentiation, and absolute value, as well as
  -- basic comparison operations.
  -- Ada provides a second pre-defined package for sin, cos, tan, cot,
  -- arcsin, arccos, arctan, arccot, and the hyperbolic versions of 
  -- those trigonometric functions.
  
  -- The package Ada.Numerics.Generic_Complex_Types requires definition
  -- with the real type to be used in the complex type definition.
  
  package Complex_Types is new Ada.Numerics.Generic_Complex_Types (Long_Float);
  use Complex_Types;
  package Complex_IO is new Ada.Text_IO.Complex_IO (Complex_Types);
  use Complex_IO;
  use Ada.Text_IO;
  
  A : Complex := Compose_From_Cartesian (Re => 1.0, Im => 1.0);
  B : Complex := Compose_From_Polar (Modulus => 1.0, Argument => 3.14159);
  C : Complex;
 

begin

  -- Addition
  C := A + B;
  Put("A + B = "); Put(C);
  New_Line;
  -- Multiplication
  C := A * B;
  Put("A * B = "); Put(C);
  New_Line;
  -- Inversion
  C := 1.0 / A;
  Put("1.0 / A = "); Put(C);
  New_Line;
  -- Negation
  C := -A;
  Put("-A = "); Put(C);
  New_Line;
  -- Conjugation
  C := Conjugate (C);

end Complex_Operations;</lang>

ALGOL 68

Works with: ALGOL 68 version Revision 1 - no extensions to language used
Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

<lang algol68>main:(

 FORMAT compl fmt = $g(-7,5)"⊥"g(-7,5)$;
 
 PROC compl operations = VOID: (
   LONG COMPL a = 1.0 ⊥ 1.0;
   LONG COMPL b = 3.14159 ⊥ 1.2;
 
   LONG COMPL c;
 
   printf(($x"a="f(compl fmt)l$,a));
   printf(($x"b="f(compl fmt)l$,b));
 
   # addition #
   c := a + b;
   printf(($x"a+b="f(compl fmt)l$,c));
   # multiplication #
   c := a * b;
   printf(($x"a*b="f(compl fmt)l$,c));
   # inversion #
   c := 1.0 / a;
   printf(($x"1/c="f(compl fmt)l$,c));
   # negation #
   c := -a;
   printf(($x"-a="f(compl fmt)l$,c))
 ); 
 compl operations

)</lang>

Output:

a=1.00000⊥1.00000
b=3.14159⊥1.20000
a+b=4.14159⊥2.20000
a*b=1.94159⊥4.34159
1/c=0.50000⊥-.50000
-a=-1.0000⊥-1.0000

APL

<lang>

  x←1j1                ⍝assignment
  y←5.25j1.5
  x+y                  ⍝addition

6.25J2.5

  x×y                  ⍝multiplication

3.75J6.75

   ⌹x                  ⍝inversion

0.5j_0.5

   -x                  ⍝negation

¯1J¯1 </lang>

AutoHotkey

contributed by Laszlo on the ahk forum <lang AutoHotkey>Cset(C,1,1) MsgBox % Cstr(C)  ; 1 + i*1 Cneg(C,C) MsgBox % Cstr(C)  ; -1 - i*1 Cadd(C,C,C) MsgBox % Cstr(C)  ; -2 - i*2 Cinv(D,C) MsgBox % Cstr(D)  ; -0.25 + 0.25*i Cmul(C,C,D) MsgBox % Cstr(C)  ; 1 + i*0

Cset(ByRef C, re, im) {

  VarSetCapacity(C,16)
  NumPut(re,C,0,"double")
  NumPut(im,C,8,"double")

} Cre(ByRef C) {

  Return NumGet(C,0,"double")

} Cim(ByRef C) {

  Return NumGet(C,8,"double")

} Cstr(ByRef C) {

  Return Cre(C) ((i:=Cim(C))<0 ? " - i*" . -i : " + i*" . i)

} Cadd(ByRef C, ByRef A, ByRef B) {

  VarSetCapacity(C,16)
  NumPut(Cre(A)+Cre(B),C,0,"double")
  NumPut(Cim(A)+Cim(B),C,8,"double")

} Cmul(ByRef C, ByRef A, ByRef B) {

  VarSetCapacity(C,16)
  t := Cre(A)*Cim(B)+Cim(A)*Cre(B)
  NumPut(Cre(A)*Cre(B)-Cim(A)*Cim(B),C,0,"double")
  NumPut(t,C,8,"double") ; A or B can be C!

} Cneg(ByRef C, ByRef A) {

  VarSetCapacity(C,16)
  NumPut(-Cre(A),C,0,"double")
  NumPut(-Cim(A),C,8,"double")

} Cinv(ByRef C, ByRef A) {

  VarSetCapacity(C,16)
  d := Cre(A)**2 + Cim(A)**2
  NumPut( Cre(A)/d,C,0,"double")
  NumPut(-Cim(A)/d,C,8,"double")

}</lang>

BASIC

Works with: QuickBasic version 4.5

<lang qbasic>TYPE complex

       real AS DOUBLE
       imag AS DOUBLE

END TYPE DECLARE SUB add (a AS complex, b AS complex, c AS complex) DECLARE SUB mult (a AS complex, b AS complex, c AS complex) DECLARE SUB inv (a AS complex, b AS complex) DECLARE SUB neg (a AS complex, b AS complex) CLS DIM x AS complex DIM y AS complex DIM z AS complex x.real = 1 x.imag = 1 y.real = 2 y.imag = 2 CALL add(x, y, z) PRINT z.real; "+"; z.imag; "i" CALL mult(x, y, z) PRINT z.real; "+"; z.imag; "i" CALL inv(x, z) PRINT z.real; "+"; z.imag; "i" CALL neg(x, z) PRINT z.real; "+"; z.imag; "i"


SUB add (a AS complex, b AS complex, c AS complex)

       c.real = a.real + b.real
       c.imag = a.imag + b.imag

END SUB

SUB inv (a AS complex, b AS complex)

       denom = a.real ^ 2 + a.imag ^ 2
       b.real = a.real / denom
       b.imag = -a.imag / denom

END SUB

SUB mult (a AS complex, b AS complex, c AS complex)

       c.real = a.real * b.real - a.imag * b.imag
       c.imag = a.real * b.imag + a.imag * b.real

END SUB

SUB neg (a AS complex, b AS complex)

       b.real = -a.real
       b.imag = -a.imag

END SUB</lang> Output:

 3 + 3 i
 0 + 4 i
 .5 +-.5 i
-1 +-1 i

BBC BASIC

<lang bbcbasic> DIM Complex{r, i}

     DIM a{} = Complex{} : a.r = 1.0 : a.i = 1.0
     DIM b{} = Complex{} : b.r = PI# : b.i = 1.2
     DIM o{} = Complex{}
     
     PROCcomplexadd(o{}, a{}, b{})
     PRINT "Result of addition is " FNcomplexshow(o{})
     PROCcomplexmul(o{}, a{}, b{})
     PRINT "Result of multiplication is " ; FNcomplexshow(o{})
     PROCcomplexneg(o{}, a{})
     PRINT "Result of negation is " ; FNcomplexshow(o{})
     PROCcomplexinv(o{}, a{})
     PRINT "Result of inversion is " ; FNcomplexshow(o{})
     END
     
     DEF PROCcomplexadd(dst{}, one{}, two{})
     dst.r = one.r + two.r
     dst.i = one.i + two.i
     ENDPROC
     
     DEF PROCcomplexmul(dst{}, one{}, two{})
     dst.r = one.r*two.r - one.i*two.i
     dst.i = one.i*two.r + one.r*two.i
     ENDPROC
     
     DEF PROCcomplexneg(dst{}, src{})
     dst.r = -src.r
     dst.i = -src.i
     ENDPROC
     
     DEF PROCcomplexinv(dst{}, src{})
     LOCAL denom : denom = src.r^2 + src.i^ 2
     dst.r = src.r / denom
     dst.i = -src.i / denom
     ENDPROC
     
     DEF FNcomplexshow(src{})
     IF src.i >= 0 THEN = STR$(src.r) + " + " +STR$(src.i) + "i"
     = STR$(src.r) + " - " + STR$(-src.i) + "i"</lang>

Output:

Result of addition is 4.14159265 + 2.2i
Result of multiplication is 1.94159265 + 4.34159265i
Result of negation is -1 - 1i
Result of inversion is 0.5 - 0.5i

C

Works with: C99

The more recent C99 standard has built-in complex number primitive types, which can be declared with float, double, or long double precision. To use these types and their associated library functions, you must include the <complex.h> header. (Note: this is a different header than the <complex> templates that are defined by C++.) [1] [2] <lang c>#include <complex.h>

  1. include <stdio.h>

void cprint(double complex c) {

 printf("%f%+fI", creal(c), cimag(c));

} void complex_operations() {

 double complex a = 1.0 + 1.0I;
 double complex b = 3.14159 + 1.2I;
 double complex c;
 printf("\na="); cprint(a);
 printf("\nb="); cprint(b);
 // addition
 c = a + b;
 printf("\na+b="); cprint(c);
 // multiplication
 c = a * b;
 printf("\na*b="); cprint(c);
 // inversion
 c = 1.0 / a;
 printf("\n1/c="); cprint(c);
 // negation
 c = -a;
 printf("\n-a="); cprint(c);
 // conjugate
 c = conj(a);
 printf("\nconj a="); cprint(c); printf("\n");

}</lang>

Works with: C89

User-defined type: <lang c>typedef struct{

       double real;
       double imag;

} Complex;

Complex add(Complex a, Complex b){

       Complex ans;
       ans.real = a.real + b.real;
       ans.imag = a.imag + b.imag;
       return ans;

}

Complex mult(Complex a, Complex b){

       Complex ans;
       ans.real = a.real * b.real - a.imag * b.imag;
       ans.imag = a.real * b.imag + a.imag * b.real;
       return ans;

}

/* it's arguable that things could be better handled if either

  a.real or a.imag is +/-inf, but that's much work */

Complex inv(Complex a){

       Complex ans;
       double denom = a.real * a.real + a.imag * a.imag;
       ans.real =  a.real / denom;
       ans.imag = -a.imag / denom;
       return ans;

}

Complex neg(Complex a){

       Complex ans;
       ans.real = -a.real;
       ans.imag = -a.imag;
       return ans;

}

Complex conj(Complex a){

       Complex ans;
       ans.real =  a.real;
       ans.imag = -a.imag;
       return ans;

}

void put(Complex c) {

       printf("%lf%+lfI", c.real, c.imag);

}

void complex_ops(void) {

 Complex a = { 1.0,     1.0 };
 Complex b = { 3.14159, 1.2 };
 
 printf("\na=");   put(a);
 printf("\nb=");   put(b);
 printf("\na+b="); put(add(a,b));
 printf("\na*b="); put(mult(a,b));
 printf("\n1/a="); put(inv(a));
 printf("\n-a=");  put(neg(a));
 printf("\nconj a=");  put(conj(a));  printf("\n");

}</lang>

C#

Works with: C sharp version 4.0

<lang csharp>namespace RosettaCode.Arithmetic.Complex {

   using System;
   using System.Numerics;
   internal static class Program
   {
       private static void Main()
       {
           var number = Complex.ImaginaryOne;
           foreach (var result in new[] { number + number, number * number, -number, 1 / number, Complex.Conjugate(number) })
           {
               Console.WriteLine(result);
           }
       }
   }

}</lang>

Works with: C sharp version 1.2

<lang csharp>using System;

public struct ComplexNumber {

   public static readonly ComplexNumber i = new ComplexNumber(0.0, 1.0);
   public static readonly ComplexNumber Zero = new ComplexNumber(0.0, 0.0);
   
   public double Re;
   public double Im;
   public ComplexNumber(double re)
   {
       this.Re = re;
       this.Im = 0;
   }
   public ComplexNumber(double re, double im)
   {
       this.Re = re;
       this.Im = im;
   }
   public static ComplexNumber operator *(ComplexNumber n1, ComplexNumber n2)
   {
       return new ComplexNumber(n1.Re * n2.Re - n1.Im * n2.Im,
           n1.Im * n2.Re + n1.Re * n2.Im);
   }
   public static ComplexNumber operator *(double n1, ComplexNumber n2)
   {
       return new ComplexNumber(n1 * n2.Re, n1 * n2.Im);
   }
   public static ComplexNumber operator /(ComplexNumber n1, ComplexNumber n2)
   {
       double n2Norm = n2.Re * n2.Re + n2.Im * n2.Im;
       return new ComplexNumber((n1.Re * n2.Re + n1.Im * n2.Im) / n2Norm,
           (n1.Im * n2.Re - n1.Re * n2.Im) / n2Norm);
   }
   public static ComplexNumber operator /(ComplexNumber n1, double n2)
   {
       return new ComplexNumber(n1.Re / n2, n1.Im / n2);
   }
   public static ComplexNumber operator +(ComplexNumber n1, ComplexNumber n2)
   {
       return new ComplexNumber(n1.Re + n2.Re, n1.Im + n2.Im);
   }
   public static ComplexNumber operator -(ComplexNumber n1, ComplexNumber n2)
   {
       return new ComplexNumber(n1.Re - n2.Re, n1.Im - n2.Im);
   }
   public static ComplexNumber operator -(ComplexNumber n)
   {
       return new ComplexNumber(-n.Re, -n.Im);
   }
   public static implicit operator ComplexNumber(double n)
   {
       return new ComplexNumber(n, 0.0);
   }
   public static explicit operator double(ComplexNumber n)
   {
       return n.Re;
   }
   public static bool operator ==(ComplexNumber n1, ComplexNumber n2)
   {
       return n1.Re == n2.Re && n1.Im == n2.Im;
   }
   public static bool operator !=(ComplexNumber n1, ComplexNumber n2)
   {
       return n1.Re != n2.Re || n1.Im != n2.Im;
   }
   public override bool Equals(object obj)
   {
       return this == (ComplexNumber)obj;
   }
   public override int GetHashCode()
   {
       return Re.GetHashCode() ^ Im.GetHashCode();
   }
   public override string ToString()
   {
       return String.Format("{0}+{1}*i", Re, Im);
   }

}

public static class ComplexMath {

   public static double Abs(ComplexNumber a)
   {
       return Math.Sqrt(Norm(a));
   }
   public static double Norm(ComplexNumber a)
   {
       return a.Re * a.Re + a.Im * a.Im;
   }
   public static double Arg(ComplexNumber a)
   {
       return Math.Atan2(a.Im, a.Re);
   }
   public static ComplexNumber Inverse(ComplexNumber a)
   {
       double norm = Norm(a);
       return new ComplexNumber(a.Re / norm, -a.Im / norm);
   }
   public static ComplexNumber Conjugate(ComplexNumber a)
   {
       return new ComplexNumber(a.Re, -a.Im);
   }
   public static ComplexNumber Exp(ComplexNumber a)
   {
       double e = Math.Exp(a.Re);
       return new ComplexNumber(e * Math.Cos(a.Im), e * Math.Sin(a.Im));
   }
   public static ComplexNumber Log(ComplexNumber a)
   {
       return new ComplexNumber(0.5 * Math.Log(Norm(a)), Arg(a));
   }
   public static ComplexNumber Power(ComplexNumber a, ComplexNumber power)
   {
       return Exp(power * Log(a));
   }
   public static ComplexNumber Power(ComplexNumber a, int power)
   {
       bool inverse = false;
       if (power < 0)
       {
           inverse = true; power = -power;
       }
       ComplexNumber result = 1.0;
       ComplexNumber multiplier = a;
       while (power > 0)
       {
           if ((power & 1) != 0) result *= multiplier;
           multiplier *= multiplier;
           power >>= 1;
       }
       if (inverse)
           return Inverse(result);
       else
           return result;
   }
   public static ComplexNumber Sqrt(ComplexNumber a)
   {
       return Exp(0.5 * Log(a));
   }
   public static ComplexNumber Sin(ComplexNumber a)
   {
       return Sinh(ComplexNumber.i * a) / ComplexNumber.i;
   }
   public static ComplexNumber Cos(ComplexNumber a)
   {
       return Cosh(ComplexNumber.i * a);
   }
   public static ComplexNumber Sinh(ComplexNumber a)
   {
       return 0.5 * (Exp(a) - Exp(-a));
   }
   public static ComplexNumber Cosh(ComplexNumber a)
   {
       return 0.5 * (Exp(a) + Exp(-a));
   }

}

class Program {

   static void Main(string[] args)
   {
       // usage
       ComplexNumber i = 2;
       ComplexNumber j = new ComplexNumber(1, -2);
       Console.WriteLine(i * j);
       Console.WriteLine(ComplexMath.Power(j, 2));
       Console.WriteLine((double)ComplexMath.Sin(i) + " vs " + Math.Sin(2));
       Console.WriteLine(ComplexMath.Power(j, 0) == 1.0);
   }

}</lang>

C++

<lang cpp>#include <iostream>

  1. include <complex>

using std::complex;

void complex_operations() {

 complex<double> a(1.0, 1.0);
 complex<double> b(3.14159, 1.25);
 // addition
 std::cout << a + b << std::endl;
 // multiplication
 std::cout << a * b << std::endl;
 // inversion
 std::cout << 1.0 / a << std::endl;
 // negation
 std::cout << -a << std::endl;
 // conjugate
 std::cout << std::conj(a) << std::endl;

}</lang>

CoffeeScript

<lang coffeescript>

  1. create an immutable Complex type

class Complex

 constructor: (@r=0, @i=0) ->
   @magnitude = @r*@r + @i*@i
 plus: (c2) ->
   new Complex(
     @r + c2.r,
     @i + c2.i
   )
 times: (c2) ->
   new Complex(
     @r*c2.r - @i*c2.i,
     @r*c2.i + @i*c2.r
   )
 negation: ->
   new Complex(
     -1 * @r,
     -1 * @i
   )
 inverse: ->
   throw Error "no inverse" if @magnitude is 0
   new Complex(
     @r / @magnitude,
     -1 * @i / @magnitude
   )
 toString: ->
   return "#{@r}" if @i == 0
   return "#{@i}i" if @r == 0
   if @i > 0
     "#{@r} + #{@i}i"
   else
     "#{@r} - #{-1 * @i}i"
     
  1. test

do ->

 a = new Complex(5, 3)
 b = new Complex(4, -3)
 
 sum = a.plus b
 console.log "(#{a}) + (#{b}) = #{sum}"
 
 product = a.times b
 console.log "(#{a}) * (#{b}) = #{product}"
 
 negation = b.negation()
 console.log "-1 * (#{b}) = #{negation}"
 
 diff = a.plus negation
 console.log "(#{a}) - (#{b}) = #{diff}"
 
 inverse = b.inverse()
 console.log "1 / (#{b}) = #{inverse}"
 
 quotient = product.times inverse
 console.log "(#{product}) / (#{b}) = #{quotient}"

</lang>

output <lang> > coffee complex.coffee (5 + 3i) + (4 - 3i) = 9 (5 + 3i) * (4 - 3i) = 29 - 3i -1 * (4 - 3i) = -4 + 3i (5 + 3i) - (4 - 3i) = 1 + 6i 1 / (4 - 3i) = 0.16 + 0.12i (29 - 3i) / (4 - 3i) = 5 + 3i </lang>

Common Lisp

Complex numbers are a built-in numeric type in Common Lisp. The literal syntax for a complex number is #C(real imaginary). The components of a complex number may be integers, ratios, or floating-point. Arithmetic operations automatically return complex (or real) numbers when appropriate:

<lang lisp>> (sqrt -1)

  1. C(0.0 1.0)

> (expt #c(0 1) 2) -1</lang>

Here are some arithmetic operations on complex numbers:

<lang lisp>> (+ #c(0 1) #c(1 0))

  1. C(1 1)

> (* #c(1 1) 2)

  1. C(2 2)

> (* #c(1 1) #c(0 2))

  1. C(-2 2)

> (- #c(1 1))

  1. C(-1 -1)

> (/ #c(0 2))

  1. C(0 -1/2)

> (conjugate #c(1 1))

  1. C(1 -1)</lang>

Complex numbers can be constructed from real and imaginary parts using the complex function, and taken apart using the realpart and imagpart functions.

<lang lisp>> (complex 64 (/ 3 4))

  1. C(64 3/4)

> (realpart #c(5 5)) 5

> (imagpart (complex 0 pi)) 3.141592653589793d0</lang>

D

Built-in complex numbers are now deprecated in D, to simplify the language. <lang d>import std.stdio, std.complex;

void main() {

   auto x = complex(1, 1); // complex of doubles on default
   auto y = complex(3.14159, 1.2);
    
   writeln(x + y);   // addition  
   writeln(x * y);   // multiplication
   writeln(1.0 / x); // inversion
   writeln(-x);      // negation

}</lang> Output:

4.14159+2.2i
1.94159+4.34159i
0.5-0.5i
-1-1i

Euphoria

<lang euphoria>constant REAL = 1, IMAG = 2 type complex(sequence s)

   return length(s) = 2 and atom(s[REAL]) and atom(s[IMAG])

end type

function add(complex a, complex b)

   return a + b

end function

function mult(complex a, complex b)

   return {a[REAL] * b[REAL] - a[IMAG] * b[IMAG],
       a[REAL] * b[IMAG] + a[IMAG] * b[REAL]}

end function

function inv(complex a)

   atom denom
   denom = a[REAL] * a[REAL] + a[IMAG] * a[IMAG]
   return {a[REAL] / denom, -a[IMAG] / denom}

end function

function neg(complex a)

   return -a

end function

function scomplex(complex a)

   sequence s
   if a[REAL] != 0 then
       s = sprintf("%g",a)
   else
       s = {}
   end if
   
   if a[IMAG] != 0 then
       if a[IMAG] = 1 then
           s &= "+i"
       elsif a[IMAG] = -1 then
           s &= "-i"
       else
           s &= sprintf("%+gi",a[IMAG])
       end if
   end if
   
   if length(s) = 0 then
       return "0"
   else
       return s
   end if

end function

complex a, b a = { 1.0, 1.0 } b = { 3.14159, 1.2 } printf(1,"a = %s\n",{scomplex(a)}) printf(1,"b = %s\n",{scomplex(b)}) printf(1,"a+b = %s\n",{scomplex(add(a,b))}) printf(1,"a*b = %s\n",{scomplex(mult(a,b))}) printf(1,"1/a = %s\n",{scomplex(inv(a))}) printf(1,"-a = %s\n",{scomplex(neg(a))})</lang>

Output:

a = 1+i
b = 3.14159+1.2i
a+b = 4.14159+2.2i
a*b = 1.94159+4.34159i
1/a = 0.5-0.5i
-a = -1-i

F#

Entered into an interactive session to show the results: <lang fsharp> > open Microsoft.FSharp.Math;;

> let a = complex 1.0 1.0;; val a : complex = 1r+1i

> let b = complex 3.14159 1.25;; val b : complex = 3.14159r+1.25i

> a + b;; val it : Complex = 4.14159r+2.25i {Conjugate = 4.14159r-2.25i;

                                  ImaginaryPart = 2.25;
                                  Magnitude = 4.713307515;
                                  Phase = 0.497661247;
                                  RealPart = 4.14159;
                                  i = 2.25;
                                  r = 4.14159;}

> a * b;; val it : Complex = 1.89159r+4.39159i {Conjugate = 1.89159r-4.39159i;

                                     ImaginaryPart = 4.39159;
                                     Magnitude = 4.781649868;
                                     Phase = 1.164082262;
                                     RealPart = 1.89159;
                                     i = 4.39159;
                                     r = 1.89159;}

> a / b;; val it : Complex =

 0.384145932435901r+0.165463215905043i
   {Conjugate = 0.384145932435901r-0.165463215905043i;
    ImaginaryPart = 0.1654632159;
    Magnitude = 0.418265673;
    Phase = 0.4067140652;
    RealPart = 0.3841459324;
    i = 0.1654632159;
    r = 0.3841459324;}

> -a;; val it : complex = -1r-1i {Conjugate = -1r+1i;

                          ImaginaryPart = -1.0;
                          Magnitude = 1.414213562;
                          Phase = -2.35619449;
                          RealPart = -1.0;
                          i = -1.0;
                          r = -1.0;}

</lang>

Factor

<lang factor>USING: combinators kernel math math.functions prettyprint ;

C{ 1 2 } C{ 0.9 -2.78 } {

   [ + . ]             ! addition
   [ - . ]             ! subtraction
   [ * . ]             ! multiplication
   [ / . ]             ! division
   [ ^ . ]             ! power

} 2cleave

C{ 1 2 } {

   [ neg . ]           ! negation
   [ 1 swap / . ]      ! multiplicative inverse
   [ conjugate . ]     ! complex conjugate
   [ sin . ]           ! sine
   [ log . ]           ! natural logarithm
   [ sqrt . ]          ! square root

} cleave</lang>

Forth

There is no standard syntax or mechanism for complex numbers. The FSL provides several implementations suitable for different uses. This example uses the existing floating point stack, but other libraries define a separate complex stack and/or a fixed-point implementation suitable for microcontrollers and DSPs.

<lang forth>include complex.seq

ZNEGATE ( r i -- -r -i ) fswap fnegate fswap fnegate ;

zvariable x zvariable y 1e 1e x z! pi 1.2e y z!

x z@ y z@ z+ z. x z@ y z@ z* z. 1+0i x z@ z/ z. x z@ znegate z.</lang>

Fortran

In ANSI FORTRAN 66 or later, COMPLEX is a built-in data type with full access to intrinsic arithmetic operations. Putting each native operation in a function is horribly inefficient, so I will simply demonstrate the operations. This example shows usage for Fortran 90 or later: <lang fortran>program cdemo

   complex :: a = (5,3), b = (0.5, 6.0)      ! complex initializer
   complex :: absum, abprod, aneg, ainv
   
   absum  = a + b
   abprod = a * b
   aneg   = -a
   ainv   = 1.0 / a

end program cdemo</lang>

And, although you did not ask, here are demonstrations of some other common complex number operations <lang fortran>program cdemo2

   complex :: a = (5,3), b = (0.5, 6)        ! complex initializer
   real, parameter :: pi = 3.141592653589793 ! The constant "pi"
   complex, parameter :: i = (0, 1)          ! the imaginary unit "i" (sqrt(-1))
   complex :: abdiff, abquot, abpow, aconj, p2cart, newc
   real :: areal, aimag, anorm, rho = 10, theta = pi / 3.0, x = 2.3, y = 3.0
   integer, parameter :: n = 50
   integer :: j
   complex, dimension(0:n-1) :: unit_circle
   
   abdiff = a - b
   abquot = a / b
   abpow  = a ** b
   areal = real(a)               ! Real part
   aimag = imag(a)               ! Imaginary part
   newc = cmplx(x,y)             ! Creating a complex on the fly from two reals intrinsically
                                 !   (initializer only works in declarations)
   newc = x + y*i                ! Creating a complex on the fly from two reals arithmetically
   anorm = abs(a)                ! Complex norm (or "modulus" or "absolute value")
                                 !   (use CABS before Fortran 90)
   aconj = conjg(a)              ! Complex conjugate (same as real(a) - i*imag(a))
   p2cart = rho * exp(i * theta) ! Euler's polar complex notation to cartesian complex notation
                                 !   conversion (use CEXP before Fortran 90)

   ! The following creates an array of N evenly spaced points around the complex unit circle
   ! useful for FFT calculations, among other things
   unit_circle = exp(2*i*pi/n * (/ (j, j=0, n-1) /) ) 

end program cdemo2</lang>

GAP

<lang gap># GAP knows gaussian integers, gaussian rationals (i.e. Q[i]), and cyclotomic fields. Here are some examples.

  1. E(n) is an nth primitive root of 1

i := Sqrt(-1);

  1. E(4)

(3 + 2*i)*(5 - 7*i);

  1. 29-11*E(4)

1/i;

  1. -E(4)

Sqrt(-3);

  1. E(3)-E(3)^2

i in GaussianIntegers;

  1. true

i/2 in GaussianIntegers;

  1. false

i/2 in GaussianRationals;

  1. true

Sqrt(-3) in Cyclotomics;

  1. true</lang>

Go

Go has complex numbers built in, with the complex conjugate in the standard library. <lang go>package main

import (

   "fmt"
   "math/cmplx"

)

func main() {

   a := 1 + 1i
   b := 3.14159 + 1.25i
   fmt.Println("a:      ", a)
   fmt.Println("b:      ", b)
   fmt.Println("a + b:  ", a+b)
   fmt.Println("a * b:  ", a*b)
   fmt.Println("-a:     ", -a)
   fmt.Println("1 / a:  ", 1/a)
   fmt.Println("a̅:      ", cmplx.Conj(a))

}</lang> Output:

a:       (1+1i)
b:       (3.14159+1.25i)
a + b:   (4.14159+2.25i)
a * b:   (1.8915899999999999+4.39159i)
-a:      (-1-1i)
1 / a:   (0.5-0.5i)
a̅:       (1-1i)

Groovy

Groovy does not provide any built-in facility for complex arithmetic. However, it does support arithmetic operator overloading. Thus it is not too hard to build a fairly robust, complete, and intuitive complex number class, such as the following: <lang groovy>class Complex {

   final Number real, imag
   
   static final Complex I = [0,1] as Complex
   
   Complex(Number real) { this(real, 0) }
   
   Complex(real, imag) { this.real = real; this.imag = imag }
   
   Complex plus (Complex c) { [real + c.real, imag + c.imag] as Complex }
   
   Complex plus (Number n) { [real + n, imag] as Complex }
   
   Complex minus (Complex c) { [real - c.real, imag - c.imag] as Complex }
   
   Complex minus (Number n) { [real - n, imag] as Complex }
   
   Complex multiply (Complex c) { [real*c.real - imag*c.imag , imag*c.real + real*c.imag] as Complex }
   
   Complex multiply (Number n) { [real*n , imag*n] as Complex }
   
   Complex div (Complex c) { this * c.recip() }
   
   Complex div (Number n) { this * (1/n) }
   
   Complex negative () { [-real, -imag] as Complex }
   
   /** the complex conjugate of this complex number.
     * Overloads the bitwise complement (~) operator. */
   Complex bitwiseNegate () { [real, -imag] as Complex }
   
   /** the magnitude of this complex number. */
  // could also use Math.sqrt( (this * (~this)).real )
   Number abs () { Math.sqrt( real*real + imag*imag ) }
   
   /** the complex reciprocal of this complex number. */
   Complex recip() { (~this) / ((this * (~this)).real) }
   
   /** derived angle θ (theta) for polar form.
     * Normalized to 0 ≤ θ < 2π. */
   Number getTheta() {
       def theta = Math.atan2(imag,real)
       theta = theta < 0 ? theta + 2 * Math.PI : theta
   }
   
   /** derived magnitude ρ (rho) for polar form. */
   Number getRho() { this.abs() }
   
   /** Runs Euler's polar-to-Cartesian complex conversion,
     * converting [ρ, θ] inputs into a [real, imag]-based complex number */
   static Complex fromPolar(Number rho, Number theta) {
       [rho * Math.cos(theta), rho * Math.sin(theta)] as Complex
   }
   
   /** Creates new complex with same magnitude ρ, but different angle θ */
   Complex withTheta(Number theta) { fromPolar(this.rho, theta) }
   
   /** Creates new complex with same angle θ, but different magnitude ρ */
   Complex withRho(Number rho) { fromPolar(rho, this.theta) }
   
   static Complex exp(Complex c) { fromPolar(Math.exp(c.real), c.imag) }
   
   static Complex log(Complex c) { [Math.log(c.rho), c.theta] as Complex }
   
   Complex power(Complex c) {
       this == 0 && c != 0  \
               ?  [0] as Complex  \
               :  c == 1  \
                       ?  this  \
                       :  exp( log(this) * c )
   }
   
   Complex power(Number n) { this ** ([n, 0] as Complex) }
   
   boolean equals(other) {
       other != null && (other instanceof Complex \
                               ? [real, imag] == [other.real, other.imag] \
                               : other instanceof Number && [real, imag] == [other, 0])
   }
   
   int hashCode() { [real, imag].hashCode() }
   
   String toString() {
       def realPart = "${real}"
       def imagPart = imag.abs() == 1 ? "i" : "${imag.abs()}i"
       real == 0 && imag == 0 \
               ? "0" \
               : real == 0 \
                       ? (imag > 0 ?  : "-")  + imagPart \
                       : imag == 0 \
                               ? realPart \
                               : realPart + (imag > 0 ? " + " : " - ")  + imagPart
   }

}</lang> Javadoc on the polar-related methods uses the following Greek alphabet encoded entities: &#x03C1;: ρ (rho), &#x03B8;: θ (theta), and &#x03C0;: π (pi).

Test Program (patterned after the Fortran example): <lang groovy>def tol = 0.000000001 // tolerance: acceptable "wrongness" to account for rounding error

println 'Demo 1: functionality as requested' def a = [5,3] as Complex println 'a == ' + a def b = [0.5,6] as Complex println 'b == ' + b

println "a + b == (${a}) + (${b}) == " + (a + b) println "a * b == (${a}) * (${b}) == " + (a * b) assert a + (-a) == 0 println "-a == -(${a}) == " + (-a) assert (a * a.recip() - 1).abs() < tol println "1/a == (${a}).recip() == " + (a.recip()) println()

println 'Demo 2: other functionality not requested, but important for completeness' println "a - b == (${a}) - (${b}) == " + (a - b) println "a / b == (${a}) / (${b}) == " + (a / b) println "a ** b == (${a}) ** (${b}) == " + (a ** b) println 'a.real == ' + a.real println 'a.imag == ' + a.imag println 'a.rho == ' + a.rho println 'a.theta == ' + a.theta println '|a| == ' + a.abs() println 'a_bar == ' + ~a

def rho = 10 def piOverTheta = 3 def theta = Math.PI / piOverTheta def fromPolar1 = Complex.fromPolar(rho, theta) // direct polar-to-cartesian conversion def fromPolar2 = Complex.exp(Complex.I * theta) * rho // Euler's equation println "rho*cos(theta) + rho*i*sin(theta) == ${rho}*cos(pi/${piOverTheta}) + ${rho}*i*sin(pi/${piOverTheta}) == " + fromPolar1 println "rho * exp(i * theta) == ${rho} * exp(i * pi/${piOverTheta}) == " + fromPolar2 assert (fromPolar1 - fromPolar2).abs() < tol println()</lang>

Output:

Demo 1: functionality as requested
a == 5 + 3i
b == 0.5 + 6i
a + b == (5 + 3i) + (0.5 + 6i) == 5.5 + 9i
a * b == (5 + 3i) * (0.5 + 6i) == -15.5 + 31.5i
-a == -(5 + 3i) == -5 - 3i
1/a == (5 + 3i).recip() == 0.1470588235 - 0.0882352941i

Demo 2: other functionality not requested, but important for completeness
a - b == (5 + 3i) - (0.5 + 6i) == 4.5 - 3i
a / b == (5 + 3i) / (0.5 + 6i) == 0.56551724145 - 0.78620689665i
a ** b == (5 + 3i) ** (0.5 + 6i) == -0.013750112198456855 - 0.09332524760169053i
a.real == 5
a.imag == 3
a.rho == 5.830951894845301
a.theta == 0.5404195002705842
|a| == 5.830951894845301
a_bar == 5 - 3i
rho*cos(theta) +  rho*i*sin(theta) == 10*cos(pi/3) +  10*i*sin(pi/3) == 5.000000000000001 + 8.660254037844386i
rho * exp(i * theta) == 10 * exp(i * pi/3) == 5.000000000000001 + 8.660254037844386i

A Groovy equivalent to the "unit circle" part of the Fortran demo is shown in the Roots of unity task.

Haskell

Complex numbers are parameterized in their base type, so you can have Complex Integer for the Gaussian Integers, Complex Float, Complex Double, etc. The operations are just the usual overloaded numeric operations.

<lang haskell>import Data.Complex

main = do

 let a = 1.0 :+ 2.0    -- complex number 1+2i
 let b = 4             -- complex number 4+0i
 -- 'b' is inferred to be complex because it's used in 
 -- arithmetic with 'a' below.
 putStrLn $ "Add:      " ++ show (a + b)
 putStrLn $ "Subtract: " ++ show (a - b)
 putStrLn $ "Multiply: " ++ show (a * b)
 putStrLn $ "Divide:   " ++ show (a / b)
 putStrLn $ "Negate:   " ++ show (-a)
 putStrLn $ "Inverse:  " ++ show (recip a)
 putStrLn $ "Conjugate:" ++ show (conjugate a)</lang>

Output:

<lang haskell>*Main> main Add: 5.0 :+ 2.0 Subtract: (-3.0) :+ 2.0 Multiply: 4.0 :+ 8.0 Divide: 0.25 :+ 0.5 Negate: (-1.0) :+ (-2.0) Inverse: 0.2 :+ (-0.4) Conjugate:1.0 :+ (-2.0)</lang>

IDL

complex (and dcomplex for double-precision) is a built-in data type in IDL:

<lang idl>x=complex(1,1)

y=complex(!pi,1.2)
print,x+y

( 4.14159, 2.20000)

print,x*y

( 1.94159, 4.34159)

print,-x

( -1.00000, -1.00000)

print,1/x

( 0.500000, -0.500000)</lang>

Icon and Unicon

Icon doesn't provide native support for complex numbers. Support is included in the IPL. <lang Icon>procedure main()

SetupComplex() a := complex(1,2) b := complex(3,4)

c := complex(&pi,1.5) d := complex(1) e := complex(,1)

every v := !"abcde" do write(v," := ",cpxstr(variable(v)))

write("a+b := ", cpxstr(cpxadd(a,b))) write("a-b := ", cpxstr(cpxsub(a,b))) write("a*b := ", cpxstr(cpxmul(a,b))) write("a/b := ", cpxstr(cpxdiv(a,b))) write("neg(a) := ", cpxstr(cpxneg(a))) write("inv(a) := ", cpxstr(cpxinv(a))) write("conj(a) := ", cpxstr(cpxconj(a))) write("abs(a) := ", cpxabs(a)) write("neg(1) := ", cpxstr(cpxneg(1))) end</lang> Icon doesn't allow for operator overloading but procedures can be overloaded as was done here to allow 'complex' to behave more robustly.

provides complex number support supplemented by the code below. <lang Icon> link complex # for complex number support

procedure SetupComplex() #: used to setup safe complex COMPLEX() # replace complex record constructor SetupComplex := 1 # never call here again return end

procedure COMPLEX(rpart,ipart) #: new safe record constructor and coercion initial complex :=: COMPLEX # get in front of record constructor return if /ipart & (type(rpart) == "complex")

  then rpart                           #                  already complex
  else COMPLEX( real(\rpart | 0.0), real(\ipart|0) )    # create a new complex number

end

procedure cpxneg(z) #: negate z

  z := complex(z)                      # coerce
  return complex( -z.rpart, -z.ipart)

end

procedure cpxinv(z) #: inverse of z

  local denom
  z := complex(z)                      # coerce
  denom := z.rpart ^ 2 + z.ipart ^ 2
  return complex(z.rpart / denom, z.ipart / denom)

end</lang> To take full advantage of the overloaded 'complex' procedure, the other cpxxxx procedures would need to be rewritten or overloaded.

Sample output:

#complexdemo.exe

a := (1.0+2.0i)
b := (3.0+4.0i)
c := (3.141592653589793+1.5i)
d := (1.0+0.0i)
e := (0.0+1.0i)
a+b := (4.0+6.0i)
a-b := (-2.0-2.0i)
a*b := (-5.0+10.0i)
a/b := (0.44+0.08i)
neg(a) := (-1.0-2.0i)
inv(a) := (0.2+0.4i)
conj(a) := (1.0-2.0i)
abs(a) := 2.23606797749979
neg(1) := (-1.0+0.0i)


This example is in need of improvement:

This could be better implemented as an object i n Unicon. Note, however, that Unicon doesn't allow for operator overloading at the current time.

J

Complex numbers are a native numeric data type in J. Although the examples shown here are performed on scalars, all numeric operations naturally apply to arrays of complex numbers. <lang j> x=: 1j1

  y=: 3.14159j1.2
  x+y

4.14159j2.2

  x*y

1.94159j4.34159

  %x

0.5j_0.5

  -x

_1j_1</lang>

Java

<lang java>public class Complex{

  public final double real;
  public final double imag;
  public Complex(){this(0,0)}//default values to 0...force of habit
  public Complex(double r, double i){real = r; imag = i;}
  public Complex add(Complex b){
     return new Complex(this.real + b.real, this.imag + b.imag);
  }
  public Complex mult(Complex b){
     //FOIL of (a+bi)(c+di) with i*i = -1
     return new Complex(this.real * b.real - this.imag * b.imag, this.real * b.imag + this.imag * b.real);
  }
  public Complex inv(){
     //1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable
     double denom = real * real + imag * imag;
     return new Complex(real/denom,-imag/denom);
  }
  public Complex neg(){
     return new Complex(-real, -imag);
  }
  public Complex conj(){
     return new Complex(real, -imag);
  }
  public String toString(){ //override Object's toString
     return real + " + " + imag + " * i";
  }
  public static void main(String[] args){
     Complex a = new Complex(Math.PI, -5) //just some numbers
     Complex b = new Complex(-1, 2.5);
     System.out.println(a.neg());
     System.out.println(a.add(b));
     System.out.println(a.inv());
     System.out.println(a.mult(b));
     System.out.println(a.conj());
  }

}</lang>

JavaScript

<lang javascript>function Complex(r, i) { this.r = r; this.i = i; }

Complex.add = function() { var num = arguments[0];

for(var i = 1, ilim = arguments.length; i < ilim; i += 1){ num.r += arguments[i].r; num.i += arguments[i].i; }

return num; }

Complex.multiply = function() { var num = arguments[0];

for(var i = 1, ilim = arguments.length; i < ilim; i += 1){ num.r = (num.r * arguments[i].r) - (num.i * arguments[i].i); num.i = (num.i * arguments[i].r) - (num.r * arguments[i].i); }

return num; }

Complex.negate = function (z) { return new Complex(-1*z.r, -1*z.i); }

Complex.invert = function(z) { var denom = Math.pow(z.r,2) + Math.pow(z.i,2); return new Complex(z.r/denom, -1*z.i/denom); }

Complex.conjugate = function(z) { return new Complex(z.r, -1*z.i); }

// BONUSES!


Complex.prototype.toString = function() { return this.r === 0 && this.i === 0

         ? "0"
         : (this.r !== 0 ? this.r : "") 
         + ((this.r !== 0 || this.i < 0) && this.i !== 0 
             ? (this.i > 0 ? "+" : "-") 
             : "" ) + ( this.i !== 0 ? Math.abs(this.i) + "i" : "" ); 

}

Complex.prototype.getMod = function() { return Math.sqrt( Math.pow(this.r,2) , Math.pow(this.i,2) ) }</lang>

Liberty BASIC

<lang lb>mainwin 50 10

print " Adding", call cprint cadd$( complex$( 1, 1), complex$( 3.14159265, 1.2)) print " Multiplying", call cprint cmulti$( complex$( 1, 1), complex$( 3.14159265, 1.2)) print " Inverting", call cprint cinv$( complex$( 1, 1)) print " Negating", call cprint cneg$( complex$( 1, 1))

end

sub cprint cx$

   print "( "; word$( cx$, 1); " + i *"; word$( cx$, 2); ")"

end sub

function complex$( a , bj ) complex number string-object constructor

 complex$ = str$( a ) ; " " ; str$( bj )

end function

function cadd$( a$ , b$ )

 ar = val( word$( a$ , 1 ) )
 ai = val( word$( a$ , 2 ) )
 br = val( word$( b$ , 1 ) )
 bi = val( word$( b$ , 2 ) )
 cadd$ = complex$( ar + br , ai + bi )

end function

function cmulti$( a$ , b$ )

 ar = val( word$( a$ , 1 ) )
 ai = val( word$( a$ , 2 ) )
 br = val( word$( b$ , 1 ) )
 bi = val( word$( b$ , 2 ) )
 cmulti$ = complex$( ar * br - ai * bi _
                   , ar * bi + ai * br )

end function

function cneg$( a$)

 ar = val( word$( a$ , 1 ) )
 ai = val( word$( a$ , 2 ) )
 cneg$ =complex$( 0 -ar, 0 -ai)

end function

function cinv$( a$)

 ar = val( word$( a$ , 1 ) )
 ai = val( word$( a$ , 2 ) )
 D =ar^2 +ai^2
 cinv$ =complex$( ar /D , 0 -ai /D )

end function</lang>

Lua

<lang lua>

--defines addition, subtraction, negation, multiplication, division, conjugation, norms, and a conversion to strgs. complex = setmetatable({ __add = function(u, v) return complex(u.real + v.real, u.imag + v.imag) end, __sub = function(u, v) return complex(u.real - v.real, u.imag - v.imag) end, __mul = function(u, v) return complex(u.real * v.real - u.imag * v.imag, u.real * v.imag + u.imag * v.real) end, __div = function(u, v) return u * complex(v.real / v.norm, -v.imag / v.norm) end, __unm = function(u) return complex(-u.real, -u.imag) end, __concat = function(u, v)

   if type(u) == "table" then return u.real .. " + " .. u.imag .. "i" .. v

elseif type(u) == "string" or type(u) == "number" then return u .. v.real .. " + " .. v.imag .. "i" end end, __index = function(u, index)

 local operations = {
   norm = function(u) return u.real ^ 2 + u.imag ^ 2 end,
   conj = function(u) return complex(u.real, -u.imag) end,
 }
 return operations[index] and operations[index](u)

end, __newindex = function() error() end }, { __call = function(z, realpart, imagpart) return setmetatable({real = realpart, imag = imagpart}, complex) end } )

local i, j = complex(2, 3), complex(1, 1)

print(i .. " + " .. j .. " = " .. (i+j)) print(i .. " - " .. j .. " = " .. (i-j)) print(i .. " * " .. j .. " = " .. (i*j)) print(i .. " / " .. j .. " = " .. (i/j)) print("|" .. i .. "| = " .. math.sqrt(i.norm)) print(i .. "* = " .. i.conj) </lang>

Maple

Maple has I (the square root of -1) built-in. Thus:

<lang maple>x := 1+I; y := Pi+I*1.2;</lang>

By itself, it will perform mathematical operations symbolically, i.e. it will not try to perform computational evaluation unless specifically asked to do so. Thus:

<lang maple>x*y;

   ==> (1 + I) (Pi + 1.2 I)

simplify(x*y);

   ==> 1.941592654 + 4.341592654 I</lang>

Other than that, the task merely asks for

<lang maple>x+y; x*y; -x; 1/x;</lang>

Mathematica

Mathematica has fully implemented support for complex numbers throughout the software. Addition, subtraction, division, multiplications and powering need no further syntax than for real numbers: <lang Mathematica>x=1+2I y=3+4I

x+y => 4 + 6 I x-y => -2 - 2 I y x => -5 + 10 I y/x => 11/5 - (2 I)/5 x^3 => -11 - 2 I y^4 => -527 - 336 I x^y => (1 + 2 I)^(3 + 4 I) N[x^y] => 0.12901 + 0.0339241 I</lang> Powering to a complex power can in general not be written shorter, so Mathematica leaves it unevaluated if the numbers are exact. An approximation can be acquired using the function N. However Mathematica goes much further, basically all functions can handle complex numbers to arbitrary precision, including (but not limited to!): <lang Mathematica>Exp Log Sin Cos Tan Csc Sec Cot ArcSin ArcCos ArcTan ArcCsc ArcSec ArcCot Sinh Cosh Tanh Csch Sech Coth ArcSinh ArcCosh ArcTanh ArcCsch ArcSech ArcCoth Sinc Haversine InverseHaversine Factorial Gamma PolyGamma LogGamma Erf BarnesG Hyperfactorial Zeta ProductLog RamanujanTauL</lang> and many many more. The documentation states:

Mathematica has fundamental support for both explicit complex numbers and symbolic complex variables. All applicable mathematical functions support arbitrary-precision evaluation for complex values of all parameters, and symbolic operations automatically treat complex variables with full generality.

MATLAB

Complex numbers are a primitive data type in MATLAB. All the typical complex operations can be performed. There are two keywords that specify a number as complex: "i" and "j".

<lang MATLAB>>> a = 1+i

a =

 1.000000000000000 + 1.000000000000000i

>> b = 3+7i

b =

 3.000000000000000 + 7.000000000000000i

>> a+b

ans =

 4.000000000000000 + 8.000000000000000i

>> a-b

ans =

-2.000000000000000 - 6.000000000000000i

>> a*b

ans =

-4.000000000000000 +10.000000000000000i

>> a/b

ans =

 0.172413793103448 - 0.068965517241379i

>> -a

ans =

-1.000000000000000 - 1.000000000000000i

>> a'

ans =

 1.000000000000000 - 1.000000000000000i

>> a^b

ans =

 0.000808197112874 - 0.011556516327187i

>> norm(a)

ans =

  1.414213562373095</lang>

Maxima

<lang maxima>z1: 5 + 2 * %i; 2*%i+5

z2: 3 - 7 * %i; 3-7*%i

carg(z1); atan(2/5)

cabs(z1); sqrt(29)

rectform(z1 * z2); 29-29*%i

polarform(z1); sqrt(29)*%e^(%i*atan(2/5))

conjugate(z1); 5-2*%i

z1 + z2; 8-5*%i

z1 - z2; 9*%i+2

z1 * z2; (3-7*%i)*(2*%i+5)

z1 * z2, rectform; 29-29*%i

z1 / z2; (2*%i+5)/(3-7*%i)

z1 / z2, rectform; (41*%i)/58+1/58

realpart(z1); 5

imagpart(z1); 2</lang>


Modula-2

<lang modula2>MODULE complex;

IMPORT InOut;

TYPE Complex = RECORD R, Im  : REAL END;

VAR z  : ARRAY [0..3] OF Complex;

PROCEDURE ShowComplex (str  : ARRAY OF CHAR; p  : Complex);

BEGIN

 InOut.WriteString (str);              InOut.WriteString (" = ");
 InOut.WriteReal (p.R, 6, 2);
 IF  p.Im >= 0.0  THEN  InOut.WriteString (" + ")  ELSE  InOut.WriteString (" - ")  END;
 InOut.WriteReal (ABS (p.Im), 6, 2);   InOut.WriteString (" i ");
 InOut.WriteLn;                        InOut.WriteBf

END ShowComplex;

PROCEDURE AddComplex (x1, x2 : Complex; VAR x3  : Complex);

BEGIN

 x3.R  := x1.R  + x2.R;
 x3.Im := x1.Im + x2.Im

END AddComplex;

PROCEDURE SubComplex (x1, x2 : Complex; VAR x3  : Complex);

BEGIN

 x3.R := x1.R - x2.R;
 x3.Im := x1.Im - x2.Im

END SubComplex;

PROCEDURE MulComplex (x1, x2  : Complex; VAR x3  : Complex);

BEGIN

 x3.R := x1.R * x2.R - x1.Im * x2.Im;
 x3.Im := x1.R * x2.Im + x1.Im * x2.R

END MulComplex;

PROCEDURE InvComplex (x1 : Complex; VAR x2  : Complex);

BEGIN

 x2.R := x1.R / (x1.R * x1.R + x1.Im * x1.Im);
 x2.Im := -1.0 * x1.Im / (x1.R * x1.R + x1.Im * x1.Im)

END InvComplex;

PROCEDURE NegComplex (x1 : Complex; VAR x2  : Complex);

BEGIN

 x2.R := - x1.R;       x2.Im := - x1.Im

END NegComplex;

BEGIN

 InOut.WriteString ("Enter two complex numbers : ");
 InOut.WriteBf;
 InOut.ReadReal (z[0].R);              InOut.ReadReal (z[0].Im);
 InOut.ReadReal (z[1].R);              InOut.ReadReal (z[1].Im);
 ShowComplex ("z1", z[0]);             ShowComplex ("z2", z[1]);
 InOut.WriteLn;
 AddComplex (z[0], z[1], z[2]);        ShowComplex ("z1 + z2", z[2]);
 SubComplex (z[0], z[1], z[2]);        ShowComplex ("z1 - z2", z[2]);
 MulComplex (z[0], z[1], z[2]);        ShowComplex ("z1 * z2", z[2]);
 InvComplex (z[0], z[2]);              ShowComplex ("1  / z1", z[2]);
 NegComplex (z[0], z[2]);              ShowComplex ("   - z1", z[2]);
 InOut.WriteLn

END complex.</lang>Output :

Enter two complex numbers : 5 3 0.5 6
z1 =   5.00 +   3.00 i
z2 =   0.50 +   6.00 i

z1 + z2 =   5.50 +   9.00 i
z1 - z2 =   4.50 -   3.00 i
z1 * z2 = -15.50 +  31.50 i
1  / z1 =   0.15 -   0.09 i
   - z1 =  -5.00 -   3.00 i

OCaml

The Complex module from the standard library provides the functionality of complex numbers: <lang ocaml>open Complex

let print_complex z =

 Printf.printf "%f + %f i\n" z.re z.im

let () =

 let a = { re = 1.0; im = 1.0 }
 and b = { re = 3.14159; im = 1.25 } in
 print_complex (add a b);
 print_complex (mul a b);
 print_complex (inv a);
 print_complex (neg a);
 print_complex (conj a)</lang>

Using Delimited Overloading, the syntax can be made closer to the usual one: <lang ocaml>let () =

 Complex.(
   let print txt z = Printf.printf "%s = %s\n" txt (to_string z) in
   let a = 1 + I
   and b = 3 + 7I in
   print "a + b" (a + b);
   print "a - b" (a - b);
   print "a * b" (a * b);
   print "a / b" (a / b);
   print "-a" (- a);
   print "conj a" (conj a);
   print "a^b" (a**b);
   Printf.printf "norm a = %g\n" (float(abs a));
 )</lang>

Octave

GNU Octave handles naturally complex numbers: <lang octave>z1 = 1.5 + 3i; z2 = 1.5 + 1.5i; disp(z1 + z2);  % 3.0 + 4.5i disp(z1 - z2);  % 0.0 + 1.5i disp(z1 * z2);  % -2.25 + 6.75i disp(z1 / z2);  % 1.5 + 0.5i disp(-z1);  % -1.5 - 3i disp(z1');  % 1.5 - 3i disp(abs(z1));  % 3.3541 = sqrt(z1*z1') disp(z1 ^ z2);  % -1.10248 - 0.38306i disp( exp(z1) );  % -4.43684 + 0.63246i disp( imag(z1) ); % 3 disp( real(z2) ); % 1.5 %...</lang>

ooRexx

<lang ooRexx> c1 = .complex~new(1, 2) c2 = .complex~new(3, 4) r = 7

say "c1 =" c1 say "c2 =" c2 say "r =" r say "-c1 =" (-c1) say "c1 + r =" c1 + r say "c1 + c2 =" c1 + c2 say "c1 - r =" c1 - r say "c1 - c2 =" c1 - c2 say "c1 * r =" c1 * r say "c1 * c2 =" c1 * c2 say "inv(c1) =" c1~inv say "conj(c1) =" c1~conjugate say "c1 / r =" c1 / r say "c1 / c2 =" c1 / c2 say "c1 == c1 =" (c1 == c1) say "c1 == c2 =" (c1 == c2)


class complex
method init
 expose r i
 use strict arg r, i = 0

-- complex instances are immutable, so these are -- read only attributes

attribute r GET
attribute i GET
method negative
 expose r i
 return self~class~new(-r, -i)
method add
 expose r i
 use strict arg other
 if other~isa(.complex) then
    return self~class~new(r + other~r, i + other~i)
 else return self~class~new(r + other, i)
method subtract
 expose r i
 use strict arg other
 if other~isa(.complex) then
    return self~class~new(r - other~r, i - other~i)
 else return self~class~new(r - other, i)
method times
 expose r i
 use strict arg other
 if other~isa(.complex) then
    return self~class~new(r * other~r - i * other~i, r * other~i + i * other~r)
 else return self~class~new(r * other, i * other)
method inv
 expose r i
 denom = r * r + i * i
 return self~class~new(r/denom, i/denom)
method conjugate
 expose r i
 return self~class~new(r, -i)
method divide
 use strict arg other
 -- this is easier if everything is a complex number
 if \other~isA(.complex) then other = .complex~new(other)
 -- division is multiplication with the inversion
 return self * other~inv
method "=="
 expose r i
 use strict arg other
 if \other~isa(.complex) then return .false
 -- Note:  these are numeric comparisons, so we're using the "="
 -- method so those are handled correctly
 return r = other~r & i = other~i
method "\=="
 use strict arg other
 return \self~"\=="(other)
method "="
 -- this is equivalent of "=="
 forward message("==")
method "\="
 -- this is equivalent of "\=="
 forward message("\==")
method "<>"
 -- this is equivalent of "\=="
 forward message("\==")
method "><"
 -- this is equivalent of "\=="
 forward message("\==")

-- some operator overrides -- these only work if the left-hand-side of the -- subexpression is a quaternion

method "*"
 forward message("TIMES")
method "/"
 forward message("DIVIDE")
method "-"
 -- need to check if this is a prefix minus or a subtract
 if arg() == 0 then
     forward message("NEGATIVE")
 else
     forward message("SUBTRACT")
method "+"
 -- need to check if this is a prefix plus or an addition
 if arg() == 0 then
     return self  -- we can return this copy since it is imutable
 else
     forward message("ADD")
method string
 expose r i
 return r self~formatnumber(i)"i"
method formatnumber private
 use arg value
 if value > 0 then return "+" value
 else return "-" value~abs

-- override hashcode for collection class hash uses

method hashCode
 expose r i
 return r~hashcode~bitxor(i~hashcode)

</lang> Output:

c1           = 1 + 2i
c2           = 3 + 4i
r            = 7
-c1          = -1 - 2i
c1 + r       = 8 + 2i
c1 + c2      = 4 + 6i
c1 - r       = -6 + 2i
c1 - c2      = -2 - 2i
c1 * r       = 7 + 14i
c1 * c2      = -5 + 10i
inv(c1)      = 0.2 + 0.4i
conj(c1)     = 1 - 2i
c1 / r       = 0.142857143 + 0.285714286i
c1 / c2      = -0.20 + 0.40i
c1 == c1     = 1
c1 == c2     = 0

OxygenBasic

Implementation of a complex numbers class with arithmetical operations, and powers using DeMoivre's theorem (polar conversion). <lang oxygenbasic> 'COMPLEX OPERATIONS '=================

type tcomplex double x,y

class Complex '============

 has tcomplex
 static sys i,pp
 static tcomplex accum[32]

def operands

 tcomplex*a,*b
 @a=@accum+i
 if pp then
   @b=@a+sizeof accum
   pp=0
 else
   @b=@this
 end if

end def

method "load"()

 operands
 a.x=b.x
 a.y=b.y

end method

method "push"()

 i+=sizeof accum

end method

method "pop"()

 pp=1
 i-=sizeof accum

end method

method "="()

 operands
 b.x=a.x
 b.y=a.y

end method

method "+"()

 operands
 a.x+=b.x
 a.y+=b.y

end method

method "-"()

 operands
 a.x-=b.x
 a.y-=b.y

end method

method "*"()

 operands
 double d
 d=a.x
 a.x = a.x * b.x - a.y * b.y
 a.y = a.y * b.x + d   * b.y

end method

method "/"()

 operands
 double d,v
 v=1/(b.x * b.x + b.y * b.y)
 d=a.x
 a.x = (a.x * b.x + a.y * b.y) * v
 a.y = (a.y * b.x - d   * b.y) * v

end method

method power(double n)

 operands
 'Using DeMoivre theorem
 double r,an,mg
 r = hypot(b.x,b.y)
 mg = r^n
 if b.x=0 then
   ay=.5*pi
   if b.y<0 then ay=-ay
 else
   an = atan(b.y,b.x)
 end if
 an  *= n 
 a.x  = mg * cos(an)
 a.y  = mg * sin(an)

end method

method show() as string

 return str(x,14) ", " str(y,14)

end method

end class

'#recordof complexop

'==== 'TEST '====

complex z1,z2,z3,z4,z5

'ENTER VALUES

z1 <= 0, 0 z2 <= 2, 1 z3 <= -2, 1 z4 <= 2, 4 z5 <= 1, 1

'EVALUATE COMPLEX EXPRESSIONS

z1 = z2 * z3 print "Z1 = "+z1.show 'RESULT -5.0, 0

z1 = z3+(z2.power(2)) print "Z1 = "+z1.show 'RESULT 1.0, 5.0


z1 = z5/z4 print "Z1 = "+z1.show 'RESULT 0.3, 0.1

z1 = z5/z1 print "Z1 = "+z1.show 'RESULT 2.0, 4.0

z1 = z2/z4 print "Z1 = "+z1.show 'RESULT -0.4, -0.3

z1 = z1*z4 print "Z1 = "+z1.show 'RESULT 2.0, 1.0 </lang>

PARI/GP

To use, type, e.g., inv(3 + 7*I). <lang parigp>add(a,b)=a+b; mult(a,b)=a*b; neg(a)=-a; inv(a)=1/a;</lang>

Pascal

<lang pascal>program showcomplex(output);

type

complex = record
           re,im: real
          end;

var

z1, z2, zr: complex;

procedure set(var result: complex; re, im: real);

begin
 result.re := re;
 result.im := im
end;

procedure print(a: complex);

begin
 write('(', a.re , ',', a.im, ')')
end;

procedure add(var result: complex; a, b: complex);

begin
 result.re := a.re + b.re;
 result.im := a.im + b.im;
end;

procedure neg(var result: complex; a: complex);

begin
 result.re := -a.re;
 result.im := -a.im
end;

procedure mult(var result: complex; a, b: complex);

begin
 result.re := a.re*b.re - a.im*b.im;
 result.im := a.re*b.im + a.im*b.re
end;

procedure inv(var result: complex; a: complex);

var
 anorm: real;
begin
 anorm := a.re*a.re + a.im*a.im;
 result.re := a.re/anorm;
 result.im := -a.im/anorm
end;

begin

set(z1, 3, 4);
set(z2, 5, 6);
neg(zr, z1);
print(zr); { prints (-3,-4) }
writeln;
add(zr, z1, z2);
print(zr); { prints (8,10) }
writeln;
inv(zr, z1);
print(zr); { prints (0.12,-0.16) }
writeln;
mul(zr, z1, z2);
print(zr); { prints (-9,38) }
writeln

end.</lang>

FreePascal has a complex units. Example of usage: <lang Pascal>Program ComplexDemo;

uses

 ucomplex;

var

 a, b, absum, abprod, aneg, ainv, acong: complex;

function complex(const re, im: real): ucomplex.complex; overload;

 begin
   complex.re := re;
   complex.im := im;
 end;

begin

 a      := complex(5, 3);
 b      := complex(0.5, 6.0);
 absum  := a + b;
 writeln ('(5 + i3) + (0.5 + i6.0): ', absum.re:3:1, ' + i', absum.im:3:1);
 abprod := a * b;
 writeln ('(5 + i3) * (0.5 + i6.0): ', abprod.re:5:1, ' + i', abprod.im:4:1);
 aneg   := -a;
 writeln ('-(5 + i3): ', aneg.re:3:1, ' + i', aneg.im:3:1);
 ainv   := 1.0 / a;
 writeln ('1/(5 + i3): ', ainv.re:3:1, ' + i', ainv.im:3:1);
 acong  := cong(a);
 writeln ('conj(5 + i3): ', acong.re:3:1, ' + i', acong.im:3:1);

end. </lang>

Perl

The Math::Complex module implements complex arithmetic. <lang perl>use Math::Complex; my $a = 1 + 1*i; my $b = 3.14159 + 1.25*i;

print "$_\n" foreach

   $a + $b,    # addition
   $a * $b,    # multiplication
   -$a,        # negation
   1 / $a,     # multiplicative inverse
   ~$a;        # complex conjugate</lang>

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

<lang perl6>my $a = 1 + i; my $b = pi + 1.25i;

.say for $a + $b, $a * $b, -$a, 1 / $a, $a.conj; .say for $a.abs, $a.sqrt, $a.re, $a.im;</lang> Output (precision varies with different implementations):

4.1415926535897931+2.25i
1.8915926535897931+4.3915926535897931i
-1-1i
0.5-0.5i
1-1i
1.4142135623730951
1.0986841134678098+0.45508986056222733i
1
1

PL/I

<lang PL/I> /* PL/I complex numbers may be integer or floating-point. */ /* In this example, the variables are floating-pint. */ /* For integer variables, change 'float' to 'fixed binary' */

declare (a, b) complex float; a = 2+5i; b = 7-6i;

put skip list (a+b); put skip list (a - b); put skip list (a*b); put skip list (a/b); put skip list (a**b); put skip list (1/a); put skip list (conjg(a)); /* gives the conjugate of 'a'. */

/* Functions exist for extracting the real and imaginary parts */ /* of a complex number. */

/* As well, trigonometric functions may be used with complex */ /* numbers, such as SIN, COS, TAN, ATAN, and so on. */ </lang>

PicoLisp

<lang PicoLisp>(load "@lib/math.l")

(de addComplex (A B)

  (cons
     (+ (car A) (car B))        # Real
     (+ (cdr A) (cdr B)) ) )    # Imag

(de mulComplex (A B)

  (cons
     (-
        (*/ (car A) (car B) 1.0)
        (*/ (cdr A) (cdr B) 1.0) )
     (+
        (*/ (car A) (cdr B) 1.0)
        (*/ (cdr A) (car B) 1.0) ) ) )

(de invComplex (A)

  (let Denom
     (+
        (*/ (car A) (car A) 1.0)
        (*/ (cdr A) (cdr A) 1.0) )
     (cons
        (*/ (car A) 1.0 Denom)
        (- (*/ (cdr A) 1.0 Denom)) ) ) )

(de negComplex (A)

  (cons (- (car A)) (- (cdr A))) )

(de fmtComplex (A)

  (pack
     (round (car A) (dec *Scl))
     (and (gt0 (cdr A)) "+")
     (round (cdr A) (dec *Scl))
     "i" ) )

(let (A (1.0 . 1.0) B (cons pi 1.2))

  (prinl "A = " (fmtComplex A))
  (prinl "B = " (fmtComplex B))
  (prinl "A+B = " (fmtComplex (addComplex A B)))
  (prinl "A*B = " (fmtComplex (mulComplex A B)))
  (prinl "1/A = " (fmtComplex (invComplex A)))
  (prinl "-A = " (fmtComplex (negComplex A))) )</lang>

Output:

A = 1.00000+1.00000i
B = 3.14159+1.20000i
A+B = 4.14159+2.20000i
A*B = 1.94159+4.34159i
1/A = 0.50000-0.50000i
-A = -1.00000-1.00000i

Pop11

Complex numbers are a built-in data type in Pop11. Real and imaginary part of complex numbers can be floating point or exact (integer or rational) value (both part must be of the same type). Operations on floating point complex numbers always produce complex numbers. Operations on exact complex numbers give real result (integer or rational) if imaginary part of the result is 0. The '+:' and '-:' operators create complex numbers: '1 -: 3' is '1 - 3i' in mathematical notation.

<lang pop11>lvars a = 1.0 +: 1.0, b = 2.0 +: 5.0 ; a+b => a*b => 1/a => a-b => a-a => a/b => a/a =>

The same, but using exact values

1 +: 1 -> a; 2 +: 5 -> b; a+b => a*b => 1/a => a-b => a-a => a/b => a/a =></lang>

PostScript

Complex numbers can be represented as 2 element vectors ( arrays ). Thus, a+bi can be written as [a b] in PostScript. <lang> %Adding two complex numbers /addcomp{ /x exch def /y exch def /z [0 0] def z 0 x 0 get y 0 get add put z 1 x 1 get y 1 get add put z pstack }def

%Subtracting one complex number from another /subcomp{ /x exch def /y exch def /z [0 0] def z 0 x 0 get y 0 get sub put z 1 x 1 get y 1 get sub put z pstack }def

%Multiplying two complex numbers /mulcomp{ /x exch def /y exch def /z [0 0] def z 0 x 0 get y 0 get mul x 1 get y 1 get mul sub put z 1 x 1 get y 0 get mul x 0 get y 1 get mul add put z pstack }def

%Negating a complex number /negcomp{ /x exch def /z [0 0] def z 0 x 0 get neg put z 1 x 1 get neg put z pstack }def

%Inverting a complex number /invcomp{ /x exch def /z [0 0] def z 0 x 0 get x 0 get 2 exp x 1 get 2 exp add div put z 0 x 1 get neg x 0 get 2 exp x 1 get 2 exp add div put z pstack }def

</lang>

PureBasic

<lang PureBasic>Structure Complex

 real.d
 imag.d

EndStructure

Procedure Add_Complex(*A.Complex, *B.Complex)

 Protected *R.Complex=AllocateMemory(SizeOf(Complex))
 If *R
   *R\real=*A\real+*B\real
   *R\imag=*A\imag+*B\imag
 EndIf
 ProcedureReturn *R

EndProcedure

Procedure Inv_Complex(*A.Complex)

 Protected *R.Complex=AllocateMemory(SizeOf(Complex)), denom.d
 If *R
   denom  = *A\real * *A\real + *A\imag * *A\imag
   *R\real= *A\real / denom
   *R\imag=-*A\imag / denom
 EndIf
 ProcedureReturn *R

EndProcedure

Procedure Mul_Complex(*A.Complex, *B.Complex)

 Protected *R.Complex=AllocateMemory(SizeOf(Complex))
 If *R
   *R\real=*A\real * *B\real - *A\imag * *B\imag
   *R\imag=*A\real * *B\imag + *A\imag * *B\real
 EndIf
 ProcedureReturn *R

EndProcedure

Procedure Neg_Complex(*A.Complex)

 Protected *R.Complex=AllocateMemory(SizeOf(Complex))
 If *R
   *R\real=-*A\real
   *R\imag=-*A\imag
 EndIf
 ProcedureReturn *R

EndProcedure

Procedure ShowAndFree(Header$, *Complex.Complex)

 If *Complex
   Protected.d i=*Complex\imag, r=*Complex\real 
   Print(LSet(Header$,7))
   Print("= "+StrD(r,3))
   If i>=0:  Print(" + ")
   Else:     Print(" - ")
   EndIf
   PrintN(StrD(Abs(i),3)+"i")
   FreeMemory(*Complex)
 EndIf

EndProcedure

If OpenConsole()

 Define.Complex a, b, *c
 a\real=1.0: a\imag=1.0
 b\real=#PI: b\imag=1.2
 *c=Add_Complex(a,b):  ShowAndFree("a+b",    *c)
 *c=Mul_Complex(a,b):  ShowAndFree("a*b",    *c)
 *c=Inv_Complex(a):    ShowAndFree("Inv(a)", *c)
 *c=Neg_Complex(a):    ShowAndFree("-a",     *c)
 Print(#CRLF$+"Press ENTER to exit"):Input()

EndIf</lang>

Python

<lang python>>>> z1 = 1.5 + 3j >>> z2 = 1.5 + 1.5j >>> z1 + z2 (3+4.5j) >>> z1 - z2 1.5j >>> z1 * z2 (-2.25+6.75j) >>> z1 / z2 (1.5+0.5j) >>> - z1 (-1.5-3j) >>> z1.conjugate() (1.5-3j) >>> abs(z1) 3.3541019662496847 >>> z1 ** z2 (-1.1024829553277784-0.38306415117199333j) >>> z1.real 1.5 >>> z1.imag 3.0 >>> </lang>

R

Translation of: Octave

<lang R>z1 <- 1.5 + 3i z2 <- 1.5 + 1.5i print(z1 + z2) # 3+4.5i print(z1 - z2) # 0+1.5i print(z1 * z2) # -2.25+6.75i print(z1 / z2) # 1.5+0.5i print(-z1) # -1.5-3i print(Conj(z1)) # 1.5-3i print(abs(z1)) # 3.354102 print(z1^z2) # -1.102483-0.383064i print(exp(z1)) # -4.436839+0.632456i print(Re(z1)) # 1.5 print(Im(z1)) # 3</lang>

REXX

The REXX language has no complex type numbers, but some complex arithmetic subroutines can easily be written. <lang rexx>/*REXX program to show how to support math functions for complex numbers*/

x = '(5,3i)' /*this little piggy uses "I" (or "i") ... */ y = '( .5, 6j)' /*this little piggy uses "J" (or "j") ... */

sum = Cadd(x,y); say ' addition: ' x " + " y ' = ' sum dif = Csub(x,y); say ' subtration: ' x " + " y ' = ' dif prod = Cmul(x,y); say 'multiplication: ' x " * " y ' = ' prod quot = Cdiv(x,y); say ' division: ' x " ÷ " y ' = ' quot inv = Cinv(x); say ' inverse: ' x " = " inv cnjX = Ccnj(x); say ' conjugate of: ' x " = " cnjX negX = Cneg(x); say ' negation of: ' x " = " negX exit /*stick a fork in it, we're done.*/

/*─────────────────────────────────────one─liners───────────────────────*/ Ccnj: procedure;arg a ',' b,c ',' d;call Cg;r1=a;r2=-b;return Cr() Cadd: procedure;arg a ',' b,c ',' d;call Cg;r1=a+c;r2=b+d;return Cr() Csub: procedure;arg a ',' b,c ',' d;call Cg;r1=a-c;r2=b-d;return Cr() Cmul: procedure;arg a ',' b,c ',' d;call Cg;r1=a*c-b*d; r2=b*c+a*d;return Cr() Cdiv: procedure;arg a ',' b,c ',' d;call Cg;_=c*c+d*d;r1=(a*c+b*d)/_;r2=(b*c-a*d)/_;return Cr() Cg: a=Cdej(a); b=Cdej(b); c=Cdej(c); d=Cdej(d); return Cr: _='['r1; if r2\=0 then _=_','r2"j"; return _']' Cdej: return word(translate(arg(1),,'{[(JI)]}') 0,1) Cneg: return Cmul(arg(1),-1) Cinv: return Cdiv(1,arg(1))</lang> output

      addition:    (5,3i)  +  (.5,6j)  =  [5.5,9j]
    subtration:    (5,3i)  +  (.5,6j)  =  [4.5,-3j]
multiplication:    (5,3i)  *  (.5,6j)  =  [-15.5,31.5j]
      division:    (5,3i)  ÷  (.5,6j)  =  [0.565517241,-0.786206897j]
       inverse:    (5,3i)              =  [0.147058824,-0.0882352941j]
  conjugate of:    (5,3i)              =  [5,-3j]
   negation of:    (5,3i)              =  [-5,-3j]

RLaB

<lang RLaB> >> x = sqrt(-1)

                       0 + 1i

>> y = 10 + 5i

                      10 + 5i

>> z = 5*x-y

                     -10 + 0i

>> isreal(z)

 1

</lang>

Ruby

<lang ruby>require 'complex' # With Ruby 1.9, this line is optional.

  1. Two ways to write complex numbers:

a = Complex(1, 1) # 1. call Kernel#Complex i = Complex::I # 2. use Complex::I b = 3.14159 + 1.25 * i

  1. Operations:

puts a + b # addition puts a * b # multiplication puts -a # negation puts 1.quo a # multiplicative inverse puts a.conjugate # complex conjugate puts a.conj # alias for complex conjugate</lang>

Notes:

  • Ruby 1.8 must require 'complex'. Ruby 1.9 moves complex numbers to core, so require 'complex' only defines a few deprecated methods.
  • Ruby 1.9 deprecates Numeric#im; code like a = 1 + 1.im or b = 3.14159 + 1.25.im would call the deprecated method.
  • All of these operations are safe with other numeric types. For example, 42.conjugate returns 42.

<lang ruby># Other ways to find the multiplicative inverse: puts 1.quo a # always works puts 1.0 / a # works, but forces floating-point math puts 1 / a # might truncate to integer</lang>

Scala

Works with: Scala version 2.8

Scala doesn't come with a Complex library, but one can be made:

<lang scala>package org.rosettacode

package object ArithmeticComplex {

 val i = Complex(0, 1)
 
 implicit def fromDouble(d: Double) = Complex(d)
 implicit def fromInt(i: Int) = Complex(i.toDouble)

}

package ArithmeticComplex {

 case class Complex(real: Double = 0.0, imag: Double = 0.0) {
   def this(s: String) = 
     this("[\\d.]+(?!i)".r findFirstIn s getOrElse "0" toDouble, 
          "[\\d.]+(?=i)".r findFirstIn s getOrElse "0" toDouble)
   
   def +(b: Complex) = Complex(real + b.real, imag + b.imag)
   def -(b: Complex) = Complex(real - b.real, imag - b.imag)
   def *(b: Complex) = Complex(real * b.real - imag * b.imag, real * b.imag + imag * b.real)
   def inverse = {
     val denom = real * real + imag * imag
     Complex(real / denom, -imag / denom)
   }
   def /(b: Complex) = this * b.inverse
   def unary_- = Complex(-real, -imag)
   lazy val abs = math.hypot(real, imag)
   override def toString = real + " + " + imag + "i"
   
   def i = { require(imag == 0.0); Complex(imag = real) }
 }
 
 object Complex {
   def apply(s: String) = new Complex(s)
   def fromPolar(rho:Double, theta:Double) = Complex(rho*math.cos(theta), rho*math.sin(theta))
 }

}</lang>

Usage example:

<lang scala>scala> import org.rosettacode.ArithmeticComplex._ import org.rosettacode.ArithmeticComplex._

scala> 1 + i res0: org.rosettacode.ArithmeticComplex.Complex = 1.0 + 1.0i

scala> 1 + 2 * i res1: org.rosettacode.ArithmeticComplex.Complex = 1.0 + 2.0i

scala> 2 + 1.i res2: org.rosettacode.ArithmeticComplex.Complex = 2.0 + 1.0i

scala> res0 + res1 res3: org.rosettacode.ArithmeticComplex.Complex = 2.0 + 3.0i

scala> res1 * res2 res4: org.rosettacode.ArithmeticComplex.Complex = 0.0 + 5.0i

scala> res2 / res0 res5: org.rosettacode.ArithmeticComplex.Complex = 1.5 + -0.5i

scala> res1.inverse res6: org.rosettacode.ArithmeticComplex.Complex = 0.2 + -0.4i

scala> -res6 res7: org.rosettacode.ArithmeticComplex.Complex = -0.2 + 0.4i </lang>

Scheme

Scheme implementations are not required to support complex numbers, but if they do, they are required to support complex number literals in one of the following standard formats[3]:

  • rectangular coordinates: real+imagi (or real-imagi), where real is the real part and imag is the imaginary part. For a pure-imaginary number, the real part may be omitted but the sign of the imaginary part is mandatory (even if it is "+"): +imagi (or -imagi). If the imaginary part is 1 or -1, the imaginary part can be omitted, leaving only the +i or -i at the end.
  • polar coordinates: r@theta, where r is the absolute value (magnitude) and theta is the angle

<lang scheme>(define a 1+i) (define b 3.14159+1.25i)

(define c (+ a b)) (define c (* a b)) (define c (/ 1 a)) (define c (- a))</lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

 include "float.s7i";
 include "complex.s7i";

const proc: main is func

 local
   var complex: a is complex(1.0, 1.0);
   var complex: b is complex(3.14159, 1.2);
 begin
   writeln("a=" <& a digits 5);
   writeln("b=" <& b digits 5);
   # addition
   writeln("a+b=" <& a + b digits 5);
   # multiplication
   writeln("a*b=" <& a * b digits 5);
   # inversion
   writeln("1/a=" <& complex(1.0) / a digits 5);
   # negation
   writeln("-a=" <& -a digits 5);
 end func;</lang>

Slate

<lang slate>[| a b |

 a: 1 + 1 i.
 b: Pi + 1.2 i.
 print: a + b.
 print: a * b.
 print: a / b.
 print: a reciprocal.
 print: a conjugated.
 print: a abs.
 print: a negated.

].</lang>

Smalltalk

Works with: GNU Smalltalk

<lang smalltalk>PackageLoader fileInPackage: 'Complex'. |a b| a := 1 + 1 i. b := 3.14159 + 1.2 i. (a + b) displayNl. (a * b) displayNl. (a / b) displayNl. a reciprocal displayNl. a conjugate displayNl. a abs displayNl. a real displayNl. a imaginary displayNl. a negated displayNl.</lang>

SNOBOL4

Works with: Macro Spitbol
Works with: Snobol4+
Works with: CSnobol

<lang SNOBOL4>* # Define complex datatype

       data('complex(r,i)')
  • # Addition
       define('addx(x1,x2)a,b,c,d') :(addx_end)

addx a = r(x1); b = i(x1); c = r(x2); d = i(x2)

       addx = complex(a + c, b + d) :(return)

addx_end

  • # Multiplication
       define('multx(x1,x2)a,b,c,d') :(multx_end)

multx a = r(x1); b = i(x1); c = r(x2); d = i(x2)

       multx = complex(a * c - b * d, b * c + a * d) :(return)

multx_end

  • # Negation
       define('negx(x)') :(negx_end)

negx negx = complex(-r(x), -i(x)) :(return) negx_end

  • # Inverse
       define('invx(x)d') :(invx_end)

invx d = (r(x) * r(x)) + (i(x) * i(x))

       invx = complex(1.0 * r(x) / d, 1.0 * -i(x) / d) :(return)

invx_end

  • # Print compex number: a+bi / a-bi
       define('printx(x)sign') :(printx_end)

printx sign = ge(i(x),0) '+'

       printx = r(x) sign i(x) 'i' :(return)

printx_end

  • # Test and display
       a = complex(1,1)
       b = complex(3.14159, 1.2)
       output = printx( addx(a,b) )
       output = printx( multx(a,b) )
       output = printx( negx(a) ) ', ' printx( negx(b) )
       output = printx( invx(a) ) ', ' printx( invx(b) )

end</lang>

Output:

4.14159+2.2i
1.94159+4.34159i
-1-1i, -3.14159-1.2i
0.5-0.5i, 0.277781125-0.106104663i

Standard ML

<lang Standard ML> (* Signature for complex numbers *) signature COMPLEX = sig

type num

val complex : real * real -> num

val negative : num -> num
val plus : num -> num -> num
val minus : num -> num -> num
val times : num -> num -> num
val invert : num -> num
val print_number : num -> unit

end;

(* Actual implementation *) structure Complex :> COMPLEX = struct

 type num = real * real
 
 fun complex (a, b) = (a, b)
 
 fun negative (a, b) = (Real.~a, Real.~b)
 fun plus (a1, b1) (a2, b2) = (Real.+ (a1, a2), Real.+(b1, b2))
 fun minus i1 i2 = plus i1 (negative i2)
 fun times (a1, b1) (a2, b2)= (Real.*(a1, a2) - Real.*(b1, b2), Real.*(a1, b2) + Real.*(a2, b1))
 fun invert (a, b) =
   let
     val denom = a * a + b * b
   in
     (a / denom, ~b / denom)
   end
 
 fun print_number (a, b) =
   print (Real.toString(a) ^ " + " ^ Real.toString(b) ^ "i\n")

end;

val i1 = Complex.complex(1.0,2.0); (* 1 + 2i *) val i2 = Complex.complex(3.0,4.0); (* 3 + 4i *)

Complex.print_number(Complex.negative(i1)); (* -1 - 2i *) Complex.print_number(Complex.plus i1 i2); (* 4 + 6i *) Complex.print_number(Complex.minus i2 i1); (* 2 + 2i *) Complex.print_number(Complex.times i1 i2); (* -5 + 10i *) Complex.print_number(Complex.invert i1); (* 1/5 - 2i/5 *) </lang>

Tcl

Library: Tcllib (Package: math::complexnumbers)

<lang tcl>package require math::complexnumbers namespace import math::complexnumbers::*

set a [complex 1 1] set b [complex 3.14159 1.2] puts [tostring [+ $a $b]] ;# ==> 4.14159+2.2i puts [tostring [* $a $b]] ;# ==> 1.94159+4.34159i puts [tostring [pow $a [complex -1 0]]] ;# ==> 0.5-0.4999999999999999i puts [tostring [- $a]] ;# ==> -1.0-i</lang>

TI-83 BASIC

TI-83 BASIC has built in complex number support; the normal arithmetic operators + - * / are used.

The method complex numbers are displayed can be chosen in the "MODE" menu.
Real: Does not show complex numbers, gives an error if a number is imaginary.
a+bi: The classic display for imaginary numbers with the real and imaginary components
re^Θi: Displays imaginary numbers in Polar Coordinates.

TI-89 BASIC

TI-89 BASIC has built-in complex number support; the normal arithmetic operators + - * / are used.

Character set note: the symbol for the imaginary unit is not the normal "i" but a different character (Unicode: U+F02F "" (private use area); this character should display with the "TI Uni" font). Also, U+3013 EN DASH “”, displayed on the TI as a superscript minus, is used for the minus sign on numbers, distinct from ASCII "-" used for subtraction.

The choice of examples here is

Translation of: Common Lisp

.

■ √(–1)                    
■ ^2                     —1
■  + 1                1 + 
■ (1+) * 2          2 + 2*
■ (1+) (2)        —2 + 2*
■ —(1+)              —1 - 
■ 1/(2)              —1 - 
■ real(1 + 2)             1
■ imag(1 + 2)             2

Complex numbers can also be entered and displayed in polar form. (This example shows input in polar form while the complex display mode is rectangular and the angle mode is radians).

■ (1∠π/4)
           √(2)/2 + √(2)/2*

Note that the parentheses around ∠ notation are required. It has a related use in vectors: (1∠π/4) is a complex number, [1,∠π/4] is a vector in two dimensions in polar notation, and [(1∠π/4)] is a complex number in a vector.

Ursala

Complex numbers are a primitive type that can be parsed in fixed or exponential formats, with either i or j notation as shown. The usual complex arithmetic and transcendental functions are callable using the syntax libname..funcname or a recognizable truncation (e.g., c..add or ..csin). Real operands are promoted to complex.

<lang Ursala>u = 3.785e+00-1.969e+00i v = 9.545e-01-3.305e+00j

  1. cast %jL

examples =

<

  complex..add (u,v),
  complex..mul (u,v),
  complex..sub (0.,u),
  complex..div (1.,v)></lang>

output:

<
   4.740e+00-5.274e+00j,
   -2.895e+00-1.439e+01j,
   3.785e+00-1.969e+00j,
   8.066e-02+2.793e-01j>