Библиотека complex — комплексная арифметика

Назначение и место в пакете

Библиотека complex (каталог src/libs/complex, один файл cmplxall.cpp) даёт набор функций над комплексными числами типа _complex. Это наследие пакета TAMIC: функции написаны в стиле языка C, принимают и возвращают числа по значению, не хранят состояния и потому могут вызываться из любого потока.

Тип _complex — структура из двух полей типа _real:

Поле Смысл
x действительная часть
y мнимая часть

В сборке пакета _real — это double (в typedef.h определён _HIGH_ACCURACY). В файлах C++ сама структура приходит из <math.h> MinGW или из преамбулы compat/include/tmc_win_prelude.h, которую компилятор подставляет в начало каждого файла src/libs, src/kernels, src/viewers.

Объявления и подробные описания всех функций — в общем заголовке src/Include/complex1.h. Справочник по функциям строится из этих комментариев автоматически (раздел «Справочник API»).

Кто пользуется библиотекой в Qt6-версии: из всех функций реально вызываются только две.

Функция Где вызывается Зачем
cabsv вьюверы TMCGROUT (графики и выражения над S-параметрами), sfile95 (s_table.cpp, s_remt.cpp) модуль элемента S-матрицы (в том числе для пересчёта в дБ)
cphase вьюверы TMCGROUT, TMCROS, TMC_DN; sfile95 фаза элемента S-матрицы

Остальные функции входят в библиотеку и описаны ради полноты; в коде Qt6-версии они не вызываются.

Состав

Файл Роль
libs/complex/cmplxall.cpp определения всех функций
include/complex1.h объявления, макросы itocx/ltocx, необязательный режим макросов INLN_COMPLEX
include/typedef.h тип _real, константы PI, REAL_MAX

Функции по группам:

Группа Функции
Части и знак aimag (мнимая часть), ctof (действительная часть), conjg (сопряжение), cneg (смена знака)
Арифметика cadd, csub, cmul, cdiv, ceq (точное равенство)
Модуль и квадраты cabsv = x2+y2, csqsum = x2+y2, csqsub = x2−y2, cabsm = x2−y2
Угол arg_cpx, cphase
Элементарные функции cexp, clog, csqrt, csin, ccos, csinh, ccosh, cpow, cpowf

Модуль числа без переполнения

cabsv, cabsm и csqsub считают с масштабированием на m=max(|x|,|y|):

|z|=m(x/m)2+(y/m)2,(1)

поэтому промежуточные квадраты не переполняются даже для чисел порядка DBL_MAX. Для z=0 сразу возвращается 0. csqsum считается напрямую, без масштабирования.

Деление

cdiv(l, r) вычисляет

lr=(lxrx+lyry)+j(rxly−lxry)rx2+ry2,(2)

знаменатель накапливается в double. Деление на ноль не вызывает исключения:

Случай Результат
l=0, r=0 0
l≠0, r=0 (REAL_MAX2, REAL_MAX2) — число с модулем REAL_MAX («бесконечность»)

Вызывающий код должен сам проверять делитель, если такая «бесконечность» недопустима.

Угол комплексного числа

В библиотеке две функции угла, и они не взаимозаменяемы.

cphase(z) — фаза на полном круге. Отсчитывается в отрицательную сторону и лежит в диапазоне (−2π,0]:

Положение z cphase
z=0 0
положительная действительная полуось 0
положительная мнимая полуось −1.5π
отрицательная действительная полуось −π
отрицательная мнимая полуось −0.5π
I квадрант (x>0,y>0) arctan(y/x)−2π, т.е. (−2π,−1.5π)
II квадрант (x<0,y>0) arctan(y/x)−π, т.е. (−1.5π,−π)
III квадрант (x<0,y<0) arctan(y/x)−π, т.е. (−π,−0.5π)
IV квадрант (x>0,y<0) arctan(y/x), т.е. (−0.5π,0)

Иначе говоря, cphase = atan2(y, x), приведённый в (−2π,0]. Именно её используют вьюверы для графиков фазы (в градусах — умножением на 180/π). Развёртка фазы между частотами выполняется уже во вьюверах, см. развёртка фазы.

arg_cpx(z) — угол через арксинус: arcsin(y/|z|), диапазон [−π/2,π/2]. Для чисел левой полуплоскости (x<0) результат неверен: arcsin не различает x и −x, поэтому, например, для z=−1 получается 0 вместо ±π. Для z=0 — деление на ноль (NaN).

На arg_cpx построены clog, csqrt и cpow, поэтому все они верны только при x≥0 (подробнее — в разделе «Подводные камни»).

Элементарные функции

Функция Формула в коде
cexp(z) ex(cosy+jsiny); при y=0 — сразу ex
clog(z) ln|z|+jarg_cpx(z)
csqrt(z) |z|(cos(θ/2)+jsin(θ/2)), θ=arg_cpx(z)
cpow(l, r) exp(r·clog(l)); при l=0 возвращается 0
csin(z) sinxcoshy+jcosxsinhy
ccos(z) cosxcoshy−jsinxsinhy
csinh(z) sinhxcosy+jcoshxsiny
ccosh(z) coshxcosy+jsinhxsiny

Режим макросов INLN_COMPLEX

Если перед включением complex1.h определить INLN_COMPLEX, функции aimag, ctof, ftoc, conjg, cneg заменяются макросами, работающими через глобальную переменную _complex z, которая объявляется прямо в заголовке. В сборке пакета этот режим не используется: макрос нигде не определён.

Подводные камни

Всё перечисленное подтверждено кодом cmplxall.cpp; в функциях, которыми пользуется пакет (cabsv, cphase), этих проблем нет.

  1. cpowf возвращает неопределённый результат. В теле логарифм берётся от неинициализированной локальной переменной z, а не от аргумента l (z = clog( z );). В коде пакета функция не вызывается.
  2. ftoc объявлена, но не определена. Макросы itocx и ltocx вызывают её, поэтому без режима INLN_COMPLEX их использование не слинкуется.
  3. arg_cpx, clog, csqrt, cpow неверны при x<0 — см. раздел «Угол комплексного числа». Для фазы используйте cphase.
  4. cabsm возвращает NaN при |y|>|x| — это корень из отрицательного числа x2−y2.
  5. cdiv при делении на ноль не сообщает об ошибке, а возвращает «бесконечность» с модулем REAL_MAX — см. «Деление».

complex library — complex arithmetic

Purpose and place in the package

The complex library (directory src/libs/complex, a single file cmplxall.cpp) provides a set of functions on complex numbers of type _complex. It is a legacy of the TAMIC package: the functions are written in C style, take and return numbers by value, keep no state and can therefore be called from any thread.

The _complex type is a structure of two fields of type _real:

Field Meaning
x real part
y imaginary part

In the package build _real is double (_HIGH_ACCURACY is defined in typedef.h). In C++ files the structure itself comes from MinGW's <math.h> or from the prelude compat/include/tmc_win_prelude.h, which the compiler inserts at the beginning of every src/libs, src/kernels, src/viewers file.

Declarations and detailed descriptions of all functions are in the shared header src/Include/complex1.h. The function reference is generated from these comments automatically (the "API reference" section).

Who uses the library in the Qt6 version: of all the functions, only two are actually called.

Function Where it is called Purpose
cabsv TMCGROUT viewers (plots and expressions over S-parameters), sfile95 (s_table.cpp, s_remt.cpp) magnitude of an S-matrix element (including conversion to dB)
cphase TMCGROUT, TMCROS, TMC_DN viewers; sfile95 phase of an S-matrix element

The remaining functions are part of the library and are described for completeness; they are not called in the Qt6 version code.

Contents

File Role
libs/complex/cmplxall.cpp definitions of all functions
include/complex1.h declarations, the itocx/ltocx macros, the optional macro mode INLN_COMPLEX
include/typedef.h the _real type, the constants PI, REAL_MAX

Functions by group:

Group Functions
Parts and sign aimag (imaginary part), ctof (real part), conjg (conjugation), cneg (sign change)
Arithmetic cadd, csub, cmul, cdiv, ceq (exact equality)
Modulus and squares cabsv = x2+y2, csqsum = x2+y2, csqsub = x2−y2, cabsm = x2−y2
Angle arg_cpx, cphase
Elementary functions cexp, clog, csqrt, csin, ccos, csinh, ccosh, cpow, cpowf

Modulus without overflow

cabsv, cabsm and csqsub compute with scaling by m=max(|x|,|y|):

|z|=m(x/m)2+(y/m)2,(1)

so the intermediate squares do not overflow even for numbers of the order of DBL_MAX. For z=0, 0 is returned immediately. csqsum is computed directly, without scaling.

Division

cdiv(l, r) computes

lr=(lxrx+lyry)+j(rxly−lxry)rx2+ry2,(2)

the denominator is accumulated in double. Division by zero does not raise an exception:

Case Result
l=0, r=0 0
l≠0, r=0 (REAL_MAX2, REAL_MAX2) — a number with modulus REAL_MAX ("infinity")

The calling code must check the divisor itself if such an "infinity" is unacceptable.

Angle of a complex number

The library has two angle functions, and they are not interchangeable.

cphase(z) — phase over the full circle. It is measured in the negative direction and lies in the range (−2π,0]:

Position of z cphase
z=0 0
positive real semi-axis 0
positive imaginary semi-axis −1.5π
negative real semi-axis −π
negative imaginary semi-axis −0.5π
quadrant I (x>0,y>0) arctan(y/x)−2π, i.e. (−2π,−1.5π)
quadrant II (x<0,y>0) arctan(y/x)−π, i.e. (−1.5π,−π)
quadrant III (x<0,y<0) arctan(y/x)−π, i.e. (−π,−0.5π)
quadrant IV (x>0,y<0) arctan(y/x), i.e. (−0.5π,0)

In other words, cphase = atan2(y, x) reduced to (−2π,0]. This is the function the viewers use for phase plots (in degrees — by multiplying by 180/π). Phase unwrapping between frequencies is done in the viewers themselves, see phase unwrapping.

arg_cpx(z) — angle via the arcsine: arcsin(y/|z|), range [−π/2,π/2]. For numbers in the left half-plane (x<0) the result is wrong: arcsin does not distinguish x from −x, so, for example, for z=−1 you get 0 instead of ±π. For z=0 — division by zero (NaN).

clog, csqrt and cpow are built on arg_cpx, so all of them are correct only for x≥0 (see the "Pitfalls" section for details).

Elementary functions

Function Formula in the code
cexp(z) ex(cosy+jsiny); for y=0 — immediately ex
clog(z) ln|z|+jarg_cpx(z)
csqrt(z) |z|(cos(θ/2)+jsin(θ/2)), θ=arg_cpx(z)
cpow(l, r) exp(r·clog(l)); for l=0, 0 is returned
csin(z) sinxcoshy+jcosxsinhy
ccos(z) cosxcoshy−jsinxsinhy
csinh(z) sinhxcosy+jcoshxsiny
ccosh(z) coshxcosy+jsinhxsiny

The INLN_COMPLEX macro mode

If INLN_COMPLEX is defined before including complex1.h, the functions aimag, ctof, ftoc, conjg, cneg are replaced by macros that work through the global variable _complex z, which is declared right in the header. This mode is not used in the package build: the macro is not defined anywhere.

Pitfalls

Everything listed below is confirmed by the code of cmplxall.cpp; the functions used by the package (cabsv, cphase) do not have these problems.

  1. cpowf returns an undefined result. In its body the logarithm is taken of the uninitialised local variable z rather than of the argument l (z = clog( z );). The function is not called in the package code.
  2. ftoc is declared but not defined. The itocx and ltocx macros call it, so without the INLN_COMPLEX mode any use of them will not link.
  3. arg_cpx, clog, csqrt, cpow are wrong for x<0 — see the section "Angle of a complex number". Use cphase for the phase.
  4. cabsm returns NaN for |y|>|x| — it is the square root of the negative number x2−y2.
  5. cdiv on division by zero does not report an error but returns an "infinity" with modulus REAL_MAX — see "Division".