A   complex number   is a number which can be written as:




a
+
b
×
i


{\displaystyle a+b\times i}


(sometimes shown as:




b
+
a
×
i


{\displaystyle b+a\times i}


where   



a


{\displaystyle a}

   and   



b


{\displaystyle b}

  are real numbers,   and   



i


{\displaystyle i}

   is   √ -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 



i


{\displaystyle i}

.



Task

 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




a
+
b
i


{\displaystyle a+bi}


is




a
−
b
i


{\displaystyle a-bi}





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.




 
(* 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 *)
 