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.




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))
  }
}