Arithmetic/Complex

From Rosetta Code
Revision as of 23:55, 8 March 2008 by rosettacode>Mwn3d (Created task with Java)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Arithmetic/Complex
You are encouraged to solve this task according to the task description, using any language you may know.

An imaginary number is a number which can be written as "a + b*i" (sometimes shown as "b + a*i") where a and b are real numbers and i is the square root of -1. Typically, imaginary 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.

Show addition, multiplication, negation, and inversion of imaginary numbers in separate functions (subtraction and division operations can be made with pairs of these operations).

Some languages have imaginary number libraries available. If your language does, show the operations. If your language does not, also show the definition of this type (print functions are not necessary).

Java

<java>public class Imag{

  public double real;
  public double imag;
  public Imag(){this(0,0)}//default values to 0...force of habit
  public Imag(double r, double i){real = r; imag = i;}
  public static Imag add(Imag a, Imag b){
     return new Imag(a.real + b.real, a.imag + b.imag);
  }
  public static Imag mult(Imag a, Imag b){
     //FOIL of (a+bi)(c+di) with i*i = -1
     return new Imag(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real);
  }
  public static Imag invert(Imag a){
     //1/(a+bi) * (a-bi)/(a-bi) = 1/(a+bi) but it's more workable
     double denom = a.real * a.real - a.imag * a.imag;
     return new Imag(a.real/denom, a.imag/denom);
  }

}</java>