C++ <numbers>
系统讲解 C++20 新增标准数学常量头文件 <numbers>(std::numbers):与传统手写常量对比、全部 13 组变量模板 *_v<T> 与 double 常量速查、编译参数 -std=c++20 及 C++17 等价高精度模板实现实测。
学完这一章,你能够
- 系统讲解 C++20 新增标准数学常量头文件 <numbers>(std::numbers):与传统手写常量对比、全部 13 组变量模板 *_v<T> 与 double 常量速查、编译参数 -std=c++20 及 C++17 等价高精度模板实现实测。
C++20 <numbers> 的引入背景与传统写法对比
在 **C++20** 之前,开发者往往手写 `const double PI = 3.14159265358979323846;` 或依赖非标准 POSIX 宏 `M_PI`,容易带来精度截断、各模块定义不一、宏污染以及泛型代码浮点类型不匹配等问题。C++20 正式引入标准头文件 **`<numbers>`**(位于 `std::numbers` 命名空间),由标准库在编译期直接提供最高目标精度的数学常量集合,具体优势对比见表 1。编译使用原生 `<numbers>` 的源码时,需显式开启 C++20 及以上标准(例如 `g++ -std=c++20 main.cpp -o main`)。
std::numbers 全部 13 组变量模板与双精度常量详解
`std::numbers` 共定义 13 个受 `std::floating_point` 概念约束的 `inline constexpr` 变量模板(`e_v<T>`、`log2e_v<T>`、`log10e_v<T>`、`pi_v<T>`、`inv_pi_v<T>`、`inv_sqrtpi_v<T>`、`ln2_v<T>`、`ln10_v<T>`、`sqrt2_v<T>`、`sqrt3_v<T>`、`inv_sqrt3_v<T>`、`egamma_v<T>`、`phi_v<T>`),可按 `float`、`double` 或 `long double` 自动适配精度;同时为每个模板提供默认 `double` 常量(如 `inline constexpr double inv_pi = inv_pi_v<double>;`、`inv_sqrtpi = inv_sqrtpi_v<double>;`、`inv_sqrt3 = inv_sqrt3_v<double>;` 等,详见表 2,需注意 `inv_pi` 精确近似值为 `0.3183098861837907`)。
典型数学计算示例与 C++17 兼容验证说明
综合演示中,配合 `<iomanip>` 的 `std::fixed` 与 `std::setprecision(15)`(对 `float` 可用 7 位、对 `long double` 可用 21 位)输出各常数,并结合 `<cmath>` 的 `std::sin`、`std::cos`、`std::log` 验证 $\sin(\pi/2)=1$、$\cos(\pi)=-1$、$\ln(e)=1$ 等恒等式,以及 `float`/`double`/`long double` 在相同表达式下的精度阶梯差异。
在具体工程应用中:示例 1 用 `pi` 与 `pi_v<long double>` 计算半径 `r = 5.0` 的圆周长(`2 * pi * r ≈ 31.4159`)和面积(`pi * r² ≈ 78.5398`);示例 2 对比 `std::exp(2.0)` 与 `std::pow(e, 2.0)`(均约 `7.38906`);示例 3 用黄金分割比 `phi` 计算宽度为 10 的黄金矩形高度(`16.1803`)并与 `(1 + std::sqrt(5.0)) / 2` 核对;示例 4 对比单精度、双精度与扩展精度 `pi_v<T>` 精度表现。因本批离线容器按 `-std=c++17` 统一编译,本站验证程序在 C++17 下用等价的 `template<typename T> inline constexpr T` 数学常量模板与 `<cmath>` 高精度数值完成了全部 13 个常数的数值与多精度实测,原生 C++20 `<numbers>` 头文件留待 `-std=c++20` 环境复核。
传统手写数学常量与 C++20 <numbers> 对比表
| 对比维度 | 传统手写写法 | C++20 <numbers> |
|---|---|---|
| 精度 | 人工截取,易少位或抄错 | 按目标浮点类型提供标准满精度 |
| 类型 | 常固定为 double 或无类型宏 | 通过 *_v<T> 模板按浮点类型自动匹配 |
| 可读性 | 魔数或命名各异(PI / M_PI) | std::numbers::pi 等统一语义命名 |
| 编译期常量 | 视写法而定,宏无作用域 | 严格保证 inline constexpr 编译期常量 |
| 规范性 | 依赖编译器扩展,跨平台易缺宏 | ISO C++20 标准库规范,跨平台一致 |
std::numbers 全部 26 项常量与变量模板速查表
| 常量/模板名称 | 数学定义与说明 | 双精度近似值 |
|---|---|---|
| e_v<T> | 自然对数底数 e(变量模板) | 2.718281828459045 |
| log2e_v<T> | 以 2 为底 e 的对数 log₂(e)(变量模板) | 1.4426950408889634 |
| log10e_v<T> | 以 10 为底 e 的对数 log₁₀(e)(变量模板) | 0.4342944819032518 |
| pi_v<T> | 圆周率 π(变量模板) | 3.141592653589793 |
| inv_pi_v<T> | 圆周率倒数 1/π(变量模板) | 0.3183098861837907 |
| inv_sqrtpi_v<T> | 1/√π(变量模板) | 0.5641895835477563 |
| ln2_v<T> | 自然对数 ln(2)(变量模板) | 0.6931471805599453 |
| ln10_v<T> | 自然对数 ln(10)(变量模板) | 2.302585092994046 |
| sqrt2_v<T> | √2(变量模板) | 1.4142135623730951 |
| sqrt3_v<T> | √3(变量模板) | 1.7320508075688772 |
| inv_sqrt3_v<T> | 1/√3(变量模板) | 0.5773502691896257 |
| egamma_v<T> | 欧拉-马歇罗尼常数 γ(变量模板) | 0.5772156649015329 |
| phi_v<T> | 黄金比例 Φ = (1 + √5) / 2(变量模板) | 1.618033988749895 |
| e | 双精度常量 e(等价于 e_v<double>) | 2.718281828459045 |
| log2e | 双精度常量 log₂(e)(等价于 log2e_v<double>) | 1.4426950408889634 |
| log10e | 双精度常量 log₁₀(e)(等价于 log10e_v<double>) | 0.4342944819032518 |
| pi | 双精度常量 π(等价于 pi_v<double>) | 3.141592653589793 |
| inv_pi | 双精度常量 1/π(等价于 inv_pi_v<double>) | 0.3183098861837907 |
| inv_sqrtpi | 双精度常量 1/√π(等价于 inv_sqrtpi_v<double>) | 0.5641895835477563 |
| ln2 | 双精度常量 ln(2)(等价于 ln2_v<double>) | 0.6931471805599453 |
| ln10 | 双精度常量 ln(10)(等价于 ln10_v<double>) | 2.302585092994046 |
| sqrt2 | 双精度常量 √2(等价于 sqrt2_v<double>) | 1.4142135623730951 |
| sqrt3 | 双精度常量 √3(等价于 sqrt3_v<double>) | 1.7320508075688772 |
| inv_sqrt3 | 双精度常量 1/√3(等价于 inv_sqrt3_v<double>) | 0.5773502691896257 |
| egamma | 双精度常量 γ(等价于 egamma_v<double>) | 0.5772156649015329 |
| phi | 双精度常量黄金比例 Φ(等价于 phi_v<double>) | 1.618033988749895 |
C++17 离线复现并高精度比对 <numbers> 全部 13 个数学常量、三角恒等式与三浮点精度
#include <cmath>
#include <cstdio>
#include <iostream>
#include <string>
#include <type_traits>
#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 '\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"; }
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
// C++17 inline constexpr variable templates mirroring C++20 <numbers> (std::numbers)
namespace cpp17_numbers {
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T e_v = static_cast<T>(2.718281828459045235360287471352662498L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T log2e_v = static_cast<T>(1.442695040888963407359924681001892137L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T log10e_v = static_cast<T>(0.434294481903251827651128918916605082L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T pi_v = static_cast<T>(3.141592653589793238462643383279502884L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T inv_pi_v = static_cast<T>(0.318309886183790671537767526745028724L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T inv_sqrtpi_v = static_cast<T>(0.564189583547756286948079451560772586L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T ln2_v = static_cast<T>(0.693147180559945309417232121458176568L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T ln10_v = static_cast<T>(2.302585092994045684017991454684364208L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T sqrt2_v = static_cast<T>(1.414213562373095048801688724209698079L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T sqrt3_v = static_cast<T>(1.732050807568877293527446341505872367L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T inv_sqrt3_v = static_cast<T>(0.577350269189625764509148780501957456L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T egamma_v = static_cast<T>(0.577215664901532860606512090082402431L);
template <typename T, std::enable_if_t<std::is_floating_point_v<T>, int> = 0>
inline constexpr T phi_v = static_cast<T>(1.618033988749894848204586834365638118L);
inline constexpr double e = e_v<double>;
inline constexpr double log2e = log2e_v<double>;
inline constexpr double log10e = log10e_v<double>;
inline constexpr double pi = pi_v<double>;
inline constexpr double inv_pi = inv_pi_v<double>;
inline constexpr double inv_sqrtpi = inv_sqrtpi_v<double>;
inline constexpr double ln2 = ln2_v<double>;
inline constexpr double ln10 = ln10_v<double>;
inline constexpr double sqrt2 = sqrt2_v<double>;
inline constexpr double sqrt3 = sqrt3_v<double>;
inline constexpr double inv_sqrt3 = inv_sqrt3_v<double>;
inline constexpr double egamma = egamma_v<double>;
inline constexpr double phi = phi_v<double>;
} // namespace cpp17_numbers
int main() {
std::vector<lab::Case> cases;
namespace num = cpp17_numbers;
// Case 1: Verify all 13 constants against <cmath> / harmonic series
double harmonic = 0.0;
const int H_N = 10000;
for (int k = 1; k <= H_N; ++k) harmonic += 1.0 / k;
double gamma_est = harmonic - std::log(static_cast<double>(H_N)) - 1.0 / (2.0 * H_N);
bool c1 =
(std::fabs(num::e - std::exp(1.0)) < 1e-15) &&
(std::fabs(num::log2e - std::log2(num::e)) < 1e-15) &&
(std::fabs(num::log10e - std::log10(num::e)) < 1e-15) &&
(std::fabs(num::pi - std::acos(-1.0)) < 1e-15) &&
(std::fabs(num::inv_pi - 1.0 / num::pi) < 1e-15) &&
(std::fabs(num::inv_sqrtpi - 1.0 / std::sqrt(num::pi)) < 1e-15) &&
(std::fabs(num::ln2 - std::log(2.0)) < 1e-15) &&
(std::fabs(num::ln10 - std::log(10.0)) < 1e-15) &&
(std::fabs(num::sqrt2 - std::sqrt(2.0)) < 1e-15) &&
(std::fabs(num::sqrt3 - std::sqrt(3.0)) < 1e-15) &&
(std::fabs(num::inv_sqrt3 - 1.0 / std::sqrt(3.0)) < 1e-15) &&
(std::fabs(num::egamma - gamma_est) < 1e-8) &&
(std::fabs(num::phi - (1.0 + std::sqrt(5.0)) / 2.0) < 1e-15);
cases.push_back({"all_13_math_constants_precision", lab::jbool(true), lab::jbool(c1), c1});
// Case 2: Trigonometric and logarithmic identities
bool c2 =
(std::fabs(std::sin(num::pi / 2.0) - 1.0) < 1e-15) &&
(std::fabs(std::cos(num::pi) + 1.0) < 1e-15) &&
(std::fabs(std::log(num::e) - 1.0) < 1e-15);
cases.push_back({"trig_and_log_identities", lab::jbool(true), lab::jbool(c2), c2});
// Case 3: Circle geometry, exponential e^x, and golden ratio phi
double r = 5.0;
double circ = 2.0 * num::pi * r;
double area = num::pi * std::pow(r, 2.0);
double exp2_fn = std::exp(2.0);
double exp2_pow = std::pow(num::e, 2.0);
double golden_h = 10.0 * num::phi;
bool c3 =
(std::fabs(circ - 31.41592653589793) < 1e-12) &&
(std::fabs(area - 78.53981633974483) < 1e-12) &&
(std::fabs(exp2_fn - exp2_pow) < 1e-14) &&
(std::fabs(golden_h - 16.18033988749895) < 1e-12) &&
(std::fabs(num::phi * num::phi - (num::phi + 1.0)) < 1e-15);
cases.push_back({"circle_exp_and_golden_ratio_apps", lab::jbool(true), lab::jbool(c3), c3});
// Case 4: Precision comparison across float, double, and long double
long double ref_pi = std::acos(-1.0L);
long double err_f = std::fabs(static_cast<long double>(num::pi_v<float>) - ref_pi);
long double err_d = std::fabs(static_cast<long double>(num::pi_v<double>) - ref_pi);
long double err_ld = std::fabs(num::pi_v<long double> - ref_pi);
bool c4 = (err_ld <= err_d) && (err_d < err_f) && (err_f < 1e-6L) && (err_d < 1e-15L);
cases.push_back({"float_double_long_double_precision", lab::jbool(true), lab::jbool(c4), c4});
lab::emit(cases);
return 0;
}
- 在 G++ C++17 容器中用 inline constexpr 变量模板复现 13 个常数,验证与 <cmath> 函数误差 <1e-15(egamma 调和级数估算 <1e-8)、圆面积/指数/黄金比及 float/double/long double 精度阶梯。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:b8dd687755a9e908dd91e688d317afffde0c4d2e1d1d231916dfce7a775f247c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:9831adca42b73ed893d352ac0a6f55ec8b6fcba94da064cfac05bee9ebd97f20
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 GCC 编译使用 `#include <numbers>` 的程序时,需要附加哪个编译选项?在 C++17 项目中该如何平滑提供同风格的泛型常量?
展开参考解答
需要附加 `-std=c++20`(或更新标准如 `-std=c++23`)。在 C++17 中可使用 `template<typename T> inline constexpr T pi_v = ...;` 配合 `std::enable_if_t<std::is_floating_point_v<T>>` 构建等价的编译期常量模板。