Level 2 : Project 6

1) We want to create a class called Complex to handle complex numbers:

Attributes:

  • re the real part of type double

  • img the imaginary part of type double


Methods:

  1. Constructor with arguments (default initialization values)

  2. Display function

  3. Function that returns the module knowing that: |z| = √(a²+b²)

  4. Function which returns the conjugate knowing that: z = a - bi

  5. Overload of the following operators:

    • + : for (complex + complex) knowing that: ( a + bi ) + ( c + di ) = ( a + c ) + ( b + d )i

    • The same for - and * knowing that : ( a + bi ) * ( c + di ) = ( ac - bd ) + ( ad + bc)i


2) Create a main() test program.




Solution :


import 'dart:math';

 

class Complex {

  double re, img;

  Complex([this.re = 0this.img = 0]);

  void display() {

    if (img >= 0)

      print("z = $re + $img i");

    else

      print("z = $re - ${-imgi"); // to avoid a+-bi

  }

 

  double module() => sqrt(re * re + img * img);

 

  Complex conjugate() => Complex(re, -img);

 

  Complex operator +(Complex c) => Complex(re + c.re, img + c.img);

  Complex operator -(Complex c) => Complex(re - c.re, img - c.img);

  Complex operator *(Complex c) =>

      Complex(re * c.re - img * c.img, re * c.img + img + c.re);

}

 

void main() {

  var c1 = Complex(), c2 = Complex(27), c3 = Complex(3, -5);

  c1.display();

  c2.display();

  c3.display();

  print(c2.module());

  c3.conjugate().display();

  (c2 + c3).display();

  (c2 - c3).display();

  (c2 * c3).display();

}



z = 0.0 + 0.0 i
z = 2.0 + 7.0 i
z = 3.0 - 5.0 i
7.280109889280518
z = 3.0 + 5.0 i
z = 5.0 + 2.0 i
z = -1.0 + 12.0 i
z = 41.0 + 0.0 i