-- ============================================================================= -- A simple module offering complex arithmetic operations -- ============================================================================= import MATH = LX.MATH.FUNCTIONS -------------------------------------------------------------------------------- -- The module interface defines operations available to the users -------------------------------------------------------------------------------- module COMPLEX with -- A complex type has 4 user-accessible fields type complex with real Re, Im -- Real and imaginary part (rectangular view) real Rho, Theta -- Modulus and argument (polar view) -- Constructor for complex numbers, rectangular form function complex(real Re := 0.0, Im := 0.0) return complex -- The constant value noted 'i' constant complex I is 0.0 i 1.0 -- Arithmetic operations function Add(complex X, Y) return complex written X+Y function Sub(complex X, Y) return complex written X-Y function Mul(complex X, Y) return complex written X*Y function Div(complex X, Y) return complex written X/Y function Neg(complex X) return complex written -X -------------------------------------------------------------------------------- -- The module implementation defines how the operations work -------------------------------------------------------------------------------- is -- The implementation of the complex type has only two fields -- The remaining fields are implemented as 'properties' (see below) type complex body is record with real Re, Im -- The constructor is rather trivial to implement function complex(real Re := 0.0, Im := 0.0) return complex is -- 'result' is an implicitly defined variable for returned value result.Re := Re result.Im := Im -- Value of 'I' - A constant can be initialized by a function constant complex I is complex(0.0, 1.0) -- Arithmetic operations -- The 'body' keyword can be used to avoid repeating the arguments function Add body is result.Re := X.Re + Y.Re result.Im := X.Im + Y.Im function Sub body is result.Re := X.Re - Y.Re result.Im := X.Im - Y.Im function Mul body is result.Re := X.Re * Y.Re - X.Im * Y.Im result.Im := X.Re * Y.Im + X.Im * Y.Re function Div body is with real Denom := Y.Re * Y.Re + Y.Im * Y.Im result.Re := (X.Re * Y.Re + X.Im * Y.Im) / Denom result.Im := (X.Im * Y.Re - X.Re * Y.Im) / Denom -- Properties implementing the Rho and Theta fields function Rho(complex Z) return real written Z.Rho is return MATH.Sqrt(Z.Re^2+Z.Im^2) function Theta(complex Z) return real written Z.Theta is return MATH.Atan2(Z.Im, Z.Re) procedure SetRho(in out complex Z; in real R) written Z.Rho := R is if Z.Re <> 0.0 or Z.Im <> 0.0 then with real Ratio := R / Rho(Z) Z.Re *= Ratio Z.Im *= Ratio else Z.Re := R Z.Im := 0.0 procedure SetTheta(in out complex Z; in real T) written Z.Theta := T is with real Rho := Z.Rho Z.Re := Rho * MATH.Cos(T) Z.Im := Rho * MATH.Sin(T)