Complex number defined as a record containing real and imaginary part, utilizing operator overloading.
operator record Complex
replaceable Real re ;
replaceable Real im ;
encapsulated operator 'constructor'
function fromReal
import Complex;
input Real re ;
input Real im=0 ;
output Complex result(re=re, im=im) ;
algorithm
end fromReal;
end 'constructor';
encapsulated operator function '0'
import Complex;
output Complex result ;
algorithm
result :=
Complex(0);
end '0';
encapsulated operator '-'
function negate
import Complex;
input Complex c1 ;
output Complex c2 ;
algorithm
c2 :=
Complex(-c1.re, -c1.im);
end negate;
function subtract
import Complex;
input Complex c1 ;
input Complex c2 ;
output Complex c3 ;
algorithm
c3 :=
Complex(c1.re - c2.re, c1.im - c2.im);
end subtract;
end '-';
encapsulated operator '*'
function multiply
import Complex;
input Complex c1 ;
input Complex c2 ;
output Complex c3 ;
algorithm
c3 :=
Complex(c1.re*c2.re - c1.im*c2.im, c1.re*c2.im + c1.im*c2.re);
end multiply;
function scalarProduct
import Complex;
input Complex c1[:] ;
input Complex c2[
size(c1,1)] ;
output Complex c3 ;
algorithm
c3 :=
Complex(0);
for i
in 1:
size(c1,1)
loop
c3 :=c3 + c1[i]*c2[i];
end for;
end scalarProduct;
end '*';
encapsulated operator function '+'
import Complex;
input Complex c1 ;
input Complex c2 ;
output Complex c3 ;
algorithm
c3 :=
Complex(c1.re + c2.re, c1.im + c2.im);
end '+';
encapsulated operator function '/'
import Complex;
input Complex c1 ;
input Complex c2 ;
output Complex c3 ;
algorithm
c3 :=
Complex((+c1.re*c2.re + c1.im*c2.im)/(c2.re*c2.re + c2.im*c2.im),
(-c1.re*c2.im + c1.im*c2.re)/(c2.re*c2.re + c2.im*c2.im));
end '/';
encapsulated operator function '^'
import Complex;
input Complex c1 ;
input Complex c2 ;
output Complex c3 ;
protected
Real lnz=0.5*
log(c1.re*c1.re + c1.im*c1.im);
Real phi=
atan2(c1.im, c1.re);
Real re=lnz*c2.re - phi*c2.im;
Real im=lnz*c2.im + phi*c2.re;
algorithm
c3 :=
Complex(
exp(re)*
cos(im),
exp(re)*
sin(im));
end '^';
encapsulated operator function '=='
import Complex;
input Complex c1 ;
input Complex c2 ;
output Boolean result ;
algorithm
result := c1.re == c2.re
and c1.im == c2.im;
end '==';
encapsulated operator function '<>'
import Complex;
input Complex c1 ;
input Complex c2 ;
output Boolean result ;
algorithm
result := c1.re <> c2.re
or c1.im <> c2.im;
end '<>';
encapsulated operator function 'String'
import Complex;
input Complex c
;
input String name="j"
;
input Integer significantDigits=6
;
output String s="";
algorithm
s :=
String(c.re, significantDigits=significantDigits);
if c.im <> 0
then
if c.im > 0
then
s := s + " + ";
else
s := s + " - ";
end if;
s := s +
String(
abs(c.im), significantDigits=significantDigits) + "*" + name;
end if;
end 'String';
end Complex;