在 C++20 之前,我们写数学常量通常是这样:
cpp
const double PI = 3.14159265358979323846;
问题非常明显:精度随手写、不统一、易写错、类型不安全。
C++20 正式引入 #include <numbers>,提供标准化数学常量集合,由编译器保证精度与类型正确性。
std::numbers 是 C++20 中引入的一个标准库模块,主要用于提供一组常用的数学常量,是一套标准数学物理常数仓库。
std::numbers位于 <numbers> 头文件中,并且包含了很多数学常量,涵盖了圆周率、自然对数的底数、黄金比例等常见常数。
C++ 使用这些常量可以提高代码的可读性、精度和效率,避免了重复定义和手动输入常数值。
std::numbers 与传统写法对比优势:
| 维度 | 传统写法 | <numbers> |
|---|---|---|
| 精度 | 随手写 | 标准高精度 |
| 类型 | 固定 | 自动匹配 |
| 可读性 | 一般 | 语义明确 |
| 编译期常量 | 不一定 | 一定 |
| 规范性 | 差 | 标准库级 |
\
std::numbers 模块包含的常量
std::numbers 命名空间下包含以下成员:
cpp
template<floating_point T> inline constexpr T e_v<T> // 自然常数e
template<floating_point T> inline constexpr T log2e_v<T> // log2e
template<floating_point T> inline constexpr T log10e_v<T> // log10e
template<floating_point T> inline constexpr T pi_v<T> // 圆周率π
template<floating_point T> inline constexpr T inv_pi_v<T> // 1/π
template<floating_point T> inline constexpr T inv_sqrtpi_v<T> //1/根号π
template<floating_point T> inline constexpr T ln2_v<T> // ln2
template<floating_point T> inline constexpr T ln10_v<T> // ln10
template<floating_point T> inline constexpr T sqrt2_v<T> //根号2
template<floating_point T> inline constexpr T sqrt3_v<T> //根号3
template<floating_point T> inline constexpr T inv_sqrt3_v<T> // 1/根号3
template<floating_point T> inline constexpr T egamma_v<T> // 欧拉常数γ
template<floating_point T> inline constexpr T phi_v<T> // 黄金分割比Φ
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 = pi_v<double>
inline constexpr double inv_sqrtpi = pi_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 = sqrt3_v<double>
inline constexpr double egamma = egamma_v<double>
inline constexpr double phi = phi_v<double>
点个赞吧