15.1 Working with complex numbers
15.1.1 Constructing and accessing complex numbers
Complex numbers can be constructed using imaginary literals. For example,
complex z = -1.1 + 2.3i;
produces the complex number \(-1.1 + 2.3i\). This only works if the
real and imaginary components are literal numerals. To construct a
complex number out of arbitrary real variables, the to_complex()
function may be used. For example, the following code will work if
x
and y
are parameters, transformed data, or local variables in a
function or model block.
real x = // ...
real y = // ...
complex z = to_complex(x, y);
The real and imaginary parts of the complex number can be accessed with getters as follows.
real x = get_real(z); // x = -1.1
real y = get_imag(z); // y = 2.3
Complex numbers can be compared using equality (or inequality), but not with greater than or less than operators. For example, after running the code above, the following code snippet will print “hello”.
complex a = 3.2 + 2i;
complex b = to_complex(3.2, 2);
if (a == b) print("hello");
15.1.2 Complex assignment and promotion
Integer- or real-valued expressions may be assigned to complex numbers, with the corresponding imaginary component set to zero.
complex z1 = 3; // int promoted to 3 + 0i
complex z2 = 3.2; // real promoted to 3.2 + 0.i
15.1.3 Complex arrays
Arrays of complex numbers work as usual and allow the usual curly bracket constructors.
complex z1; complex z2; complex z3;
// ...
array[3] complex zs = { z1, z2, z3 };
for (z in zs) {
print(z);
}
Complex arrays allow assignment into their elements, with integer or real assigned values being promoted to complex.
15.1.4 Complex functions
All of the standard complex functions are available, including
natural logarithm log(z)
, natural exponentiation exp(z)
, and
powers pow(z1, z2)
, as well as all of the trig and hyperbolic
trigonometric functions and their inverse, such as sin(z)
,
acos(z)
, tanh(z)
and asinh(z)
.
Promotion also works for complex-valued function arguments, which may be passed integer or real values, which will be promoted before the function is evaluated. For example, the following user-defined complex function will accept integer, real, or complex arguments.
complex times_i(complex z) {
complex i = to_complex(0, 1);
return i * z;
}
For instance, times_i(1)
evaluates to the imaginary base \(i\), as
does times_i(1.0)
.