C++ <complex>
讲解复数类模板 std::complex<T> 的数学定义、实部虚部访问、四则与复变超越函数、极坐标构造 std::polar 以及浮点特化规则,并在离线 G++ C++17 容器实测。
学完这一章,你能够
- 讲解复数类模板 std::complex<T> 的数学定义、实部虚部访问、四则与复变超越函数、极坐标构造 std::polar 以及浮点特化规则,并在离线 G++ C++17 容器实测。
复数表示、模板特化与基础输出
在信号处理、快速傅里叶变换(FFT)与交流电路分析等领域,复数 $z = a + bi$(其中 $a$ 为实部、$b$ 为虚部、虚数单位 $i$ 满足 $i^2 = -1$)是最基本的数据类型。C++ 标准库 `<complex>` 提供类模板 `std::complex<T>`,标准明确支持三种浮点特化:`std::complex<float>`、`std::complex<double>`(最常用)与 `std::complex<long double>`(使用非浮点类型实例化在标准中属于未指定行为)。包含 `#include <complex>` 后,流运算符 `operator<<` 会将复数按 `(real,imag)` 形式格式化输出,例如 `std::complex<double>(3.0, 4.0)` 输出为 `(3,4)`。
成员访问、四则运算与复变数学函数
创建复数后,可通过成员函数 `c.real()` 与 `c.imag()` 读取(或在 C++11+ 中以带参重载修改)实部与虚部。`<complex>` 重载了 `+`、`-`、`*`、`/` 四则运算符,例如对 `z1(3,4)` 与 `z2(1,-2)`,和为 `(4,2)`、差为 `(2,6)`、积为 `(11,-2)`、商为 `(-1,2)`。
库内还提供丰富的复数函数:`std::conj` 求共轭复数,`std::abs` 求模长 $|z| = \sqrt{a^2+b^2}$,`std::arg` 求主辐角(弧度制,范围 $(-\pi, \pi]$),以及复变指数与三角函数 `std::exp`、`std::sin`、`std::cos` 等。若已知极坐标模长 $r$ 与相角 $\theta$,可调用 `std::polar(r, theta)` 直接构造复数(注:`M_PI` 为 POSIX 扩展宏而非严格 ISO C++17 标准宏,跨平台可写 `const double pi = std::acos(-1.0);`)。
完整综合示例与离线精度验证
综合示例以 `c1(5.0, 3.0)` 与 `c2(2.0, -4.0)` 演示完整流程:和为 `(7,-1)`、差为 `(3,7)`、积为 `(22,-14)`、商为 `(-0.1,1.3)`、共轭 `std::conj(c1)` 为 `(5,-3)`、模长 `std::abs(c1) = \sqrt{34} \approx 5.83095`、辐角 `std::arg(c1) = \arctan(3/5) \approx 0.54042` 弧度。本站离线实验已对三种浮点特化、四则运算、欧拉公式 $e^{i\pi} = -1$ 及极坐标往返进行双精度误差校验。
实测 std::complex 构造与输出、四则运算、共轭/模/辐角/欧拉恒等式及极坐标转换
#include <cmath>
#include <complex>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
bool near(double a, double b, double eps = 1e-6) {
return std::fabs(a - b) <= eps;
}
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
int main() {
std::vector<lab::Case> cases;
// Case 1: construction, real()/imag(), stream format, float/double/long double specializations
std::complex<double> z1(3.0, 4.0);
std::complex<float> zf(1.0f, 2.0f);
std::complex<long double> zld(2.0L, -3.0L);
std::ostringstream oss;
oss << z1;
bool ok1 = (oss.str() == "(3,4)")
&& lab::near(z1.real(), 3.0) && lab::near(z1.imag(), 4.0)
&& lab::near(zf.real(), 1.0) && lab::near(zf.imag(), 2.0)
&& lab::near(static_cast<double>(zld.real()), 2.0) && lab::near(static_cast<double>(zld.imag()), -3.0);
cases.push_back({
"complex_construct_and_parts",
lab::jbool(true),
lab::jbool(ok1),
ok1
});
// Case 2: four arithmetic operations on (5+3i) and (2-4i)
std::complex<double> c1(5.0, 3.0);
std::complex<double> c2(2.0, -4.0);
auto sum = c1 + c2;
auto diff = c1 - c2;
auto prod = c1 * c2;
auto quot = c1 / c2;
bool ok2 = lab::near(sum.real(), 7.0) && lab::near(sum.imag(), -1.0)
&& lab::near(diff.real(), 3.0) && lab::near(diff.imag(), 7.0)
&& lab::near(prod.real(), 22.0) && lab::near(prod.imag(), -14.0)
&& lab::near(quot.real(), -0.1) && lab::near(quot.imag(), 1.3);
cases.push_back({
"complex_arithmetic_ops",
lab::jbool(true),
lab::jbool(ok2),
ok2
});
// Case 3: conj, abs, arg, exp, sin, cos (including Euler identity)
const double pi = std::acos(-1.0);
auto cj = std::conj(c1);
double mod_z1 = std::abs(z1);
double mod_c1 = std::abs(c1);
double arg_c1 = std::arg(c1);
auto euler = std::exp(std::complex<double>(0.0, pi));
auto sin_val = std::sin(std::complex<double>(pi / 2.0, 0.0));
auto cos_val = std::cos(std::complex<double>(0.0, 0.0));
bool ok3 = lab::near(cj.real(), 5.0) && lab::near(cj.imag(), -3.0)
&& lab::near(mod_z1, 5.0)
&& lab::near(mod_c1, std::sqrt(34.0))
&& lab::near(arg_c1, std::atan2(3.0, 5.0))
&& lab::near(euler.real(), -1.0) && lab::near(euler.imag(), 0.0)
&& lab::near(sin_val.real(), 1.0) && lab::near(sin_val.imag(), 0.0)
&& lab::near(cos_val.real(), 1.0) && lab::near(cos_val.imag(), 0.0);
cases.push_back({
"complex_conj_abs_arg_transcendental",
lab::jbool(true),
lab::jbool(ok3),
ok3
});
// Case 4: std::polar(r, theta) roundtrip
double r = 5.0;
double theta = pi / 4.0;
std::complex<double> zp = std::polar(r, theta);
double expected_comp = 5.0 * std::sqrt(2.0) / 2.0;
bool ok4 = lab::near(zp.real(), expected_comp)
&& lab::near(zp.imag(), expected_comp)
&& lab::near(std::abs(zp), r)
&& lab::near(std::arg(zp), theta);
cases.push_back({
"complex_polar_representation",
lab::jbool(true),
lab::jbool(ok4),
ok4
});
lab::emit(cases);
return 0;
}
- 确认 float/double/long double 构造与流格式 (3,4)、(5+3i) 与 (2-4i) 四则精确结果、conj/abs/arg 与 exp(i*pi)==-1,以及 std::polar(5, pi/4) 往返误差小于 1e-6。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:fe4c942e59e8a8cb1171582e7d85a4e943c28f66fec90fd1cdd26e3098b67837
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:7c98e9dfae63213c3b17b15c5a06315c75641b246be0e83d3f45282b3d8b6f49
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在严格标准 C++17 代码中使用 `std::polar(r, theta)` 时,为什么不建议直接假设 `M_PI` 宏一定存在?
展开参考解答
`M_PI` 属于 POSIX 扩展而非 ISO C++17 标准强制定义的宏,在部分编译器(如 MSVC 或启用严格 `-std=c++17` 无 GNU 扩展时)可能未定义;可通过 `std::acos(-1.0)` 计算 π(或在 C++20 中使用 `<numbers>` 的 `std::numbers::pi`)。