Arithmetic/Complex

From Rosetta Code
Revision as of 03:36, 9 March 2008 by rosettacode>Mwn3d (→‎{{header|Java}}: Forgot negation (sorry Waldorf))
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).

Ada

<ada>with Ada.Numerics.Generic_Complex_Types;

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 Imaginary_Type is new Ada.Numerics.Generic_Complex_Types(Long_Float);
  use Imaginary_Type;
  
  A : Complex := Compose_From_Cartesian(Re => 1.0, Im => 1.0);
  B : Complex := Compose_From_Cartesian(Re => 3.14159, Im => 1.25);
  C : Complex;
 

begin

  -- Addition
  C := A + B;
  -- Multiplication
  C := A * B;
  -- Inversion
  C := 1.0 / A;

end Complex_Operations;</ada>

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);
  }
  public static Imag neg(Imag a){
     return new Imag(-a.real, -a.imag);
  }

}</java>