Библиотека 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 = , csqsum = , csqsub = , cabsm = |
| Угол | arg_cpx, cphase |
| Элементарные функции | cexp, clog, csqrt, csin, ccos, csinh, ccosh, cpow, cpowf |
Модуль числа без переполнения
cabsv, cabsm и csqsub считают с масштабированием на :
поэтому промежуточные квадраты не переполняются даже для чисел порядка DBL_MAX.
Для сразу возвращается 0. csqsum считается напрямую, без масштабирования.
Деление
cdiv(l, r) вычисляет
знаменатель накапливается в double. Деление на ноль не вызывает исключения:
| Случай | Результат |
|---|---|
| , | |
| , | — число с модулем REAL_MAX («бесконечность») |
Вызывающий код должен сам проверять делитель, если такая «бесконечность» недопустима.
Угол комплексного числа
В библиотеке две функции угла, и они не взаимозаменяемы.
cphase(z) — фаза на полном круге. Отсчитывается в отрицательную сторону и лежит
в диапазоне :
Положение z |
cphase |
|---|---|
| положительная действительная полуось | |
| положительная мнимая полуось | |
| отрицательная действительная полуось | |
| отрицательная мнимая полуось | |
| I квадрант () | , т.е. |
| II квадрант () | , т.е. |
| III квадрант () | , т.е. |
| IV квадрант () | , т.е. |
Иначе говоря, cphase = atan2(y, x), приведённый в . Именно её
используют вьюверы для графиков фазы (в градусах — умножением на ). Развёртка
фазы между частотами выполняется уже во вьюверах, см.
развёртка фазы.
arg_cpx(z) — угол через арксинус: , диапазон .
Для чисел левой полуплоскости () результат неверен: не различает
и , поэтому, например, для получается вместо . Для —
деление на ноль (NaN).
На arg_cpx построены clog, csqrt и cpow, поэтому все они верны только при
(подробнее — в разделе «Подводные камни»).
Элементарные функции
| Функция | Формула в коде |
|---|---|
cexp(z) |
; при — сразу |
clog(z) |
|
csqrt(z) |
, |
cpow(l, r) |
; при возвращается |
csin(z) |
|
ccos(z) |
|
csinh(z) |
|
ccosh(z) |
Режим макросов INLN_COMPLEX
Если перед включением complex1.h определить INLN_COMPLEX, функции aimag, ctof,
ftoc, conjg, cneg заменяются макросами, работающими через глобальную переменную
_complex z, которая объявляется прямо в заголовке. В сборке пакета этот режим не
используется: макрос нигде не определён.
Подводные камни
Всё перечисленное подтверждено кодом cmplxall.cpp; в функциях, которыми пользуется
пакет (cabsv, cphase), этих проблем нет.
cpowfвозвращает неопределённый результат. В теле логарифм берётся от неинициализированной локальной переменнойz, а не от аргументаl(z = clog( z );). В коде пакета функция не вызывается.ftocобъявлена, но не определена. Макросыitocxиltocxвызывают её, поэтому без режимаINLN_COMPLEXих использование не слинкуется.arg_cpx,clog,csqrt,cpowневерны при — см. раздел «Угол комплексного числа». Для фазы используйтеcphase.cabsmвозвращает NaN при — это корень из отрицательного числа .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 = , csqsum = , csqsub = , cabsm = |
| 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 :
so the intermediate squares do not overflow even for numbers of the order of DBL_MAX.
For , 0 is returned immediately. csqsum is computed directly, without scaling.
Division
cdiv(l, r) computes
the denominator is accumulated in double. Division by zero does not raise an exception:
| Case | Result |
|---|---|
| , | |
| , | — 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 :
Position of z |
cphase |
|---|---|
| positive real semi-axis | |
| positive imaginary semi-axis | |
| negative real semi-axis | |
| negative imaginary semi-axis | |
| quadrant I () | , i.e. |
| quadrant II () | , i.e. |
| quadrant III () | , i.e. |
| quadrant IV () | , i.e. |
In other words, cphase = atan2(y, x) reduced to . This is the function
the viewers use for phase plots (in degrees — by multiplying by ). Phase
unwrapping between frequencies is done in the viewers themselves, see
phase unwrapping.
arg_cpx(z) — angle via the arcsine: , range .
For numbers in the left half-plane () the result is wrong: does not distinguish
from , so, for example, for you get instead of . For —
division by zero (NaN).
clog, csqrt and cpow are built on arg_cpx, so all of them are correct only for
(see the "Pitfalls" section for details).
Elementary functions
| Function | Formula in the code |
|---|---|
cexp(z) |
; for — immediately |
clog(z) |
|
csqrt(z) |
, |
cpow(l, r) |
; for , is returned |
csin(z) |
|
ccos(z) |
|
csinh(z) |
|
ccosh(z) |
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.
cpowfreturns an undefined result. In its body the logarithm is taken of the uninitialised local variablezrather than of the argumentl(z = clog( z );). The function is not called in the package code.ftocis declared but not defined. Theitocxandltocxmacros call it, so without theINLN_COMPLEXmode any use of them will not link.arg_cpx,clog,csqrt,cpoware wrong for — see the section "Angle of a complex number". Usecphasefor the phase.cabsmreturns NaN for — it is the square root of the negative number .cdivon division by zero does not report an error but returns an "infinity" with modulusREAL_MAX— see "Division".