1.. title:: clang-tidy - modernize-use-std-numbers 2 3modernize-use-std-numbers 4========================= 5 6Finds constants and function calls to math functions that can be replaced 7with C++20's mathematical constants from the ``numbers`` header and offers 8fix-it hints. 9Does not match the use of variables with that value, and instead, 10offers a replacement for the definition of those variables. 11Function calls that match the pattern of how the constant is calculated are 12matched and replaced with the ``std::numbers`` constant. 13The use of macros gets replaced with the corresponding ``std::numbers`` 14constant, instead of changing the macro definition. 15 16The following list of constants from the ``numbers`` header are supported: 17 18* ``e`` 19* ``log2e`` 20* ``log10e`` 21* ``pi`` 22* ``inv_pi`` 23* ``inv_sqrtpi`` 24* ``ln2`` 25* ``ln10`` 26* ``sqrt2`` 27* ``sqrt3`` 28* ``inv_sqrt3`` 29* ``egamma`` 30* ``phi`` 31 32The list currently includes all constants as of C++20. 33 34The replacements use the type of the matched constant and can remove explicit 35casts, i.e., switching between ``std::numbers::e``, 36``std::numbers::e_v<float>`` and ``std::numbers::e_v<long double>`` where 37appropriate. 38 39.. code-block:: c++ 40 41 double sqrt(double); 42 double log2(double); 43 void sink(auto&&) {} 44 void floatSink(float); 45 46 #define MY_PI 3.1415926 47 48 void foo() { 49 const double Pi = 3.141592653589; // const double Pi = std::numbers::pi 50 const auto Use = Pi / 2; // no match for Pi 51 static constexpr double Euler = 2.7182818; // static constexpr double Euler = std::numbers::e; 52 53 log2(exp(1)); // std::numbers::log2e; 54 log2(Euler); // std::numbers::log2e; 55 1 / sqrt(MY_PI); // std::numbers::inv_sqrtpi; 56 sink(MY_PI); // sink(std::numbers::pi); 57 floatSink(MY_PI); // floatSink(std::numbers::pi); 58 floatSink(static_cast<float>(MY_PI)); // floatSink(std::numbers::pi_v<float>); 59 } 60 61Options 62------- 63 64.. option:: DiffThreshold 65 66 A floating point value that sets the detection threshold for when literals 67 match a constant. A literal matches a constant if 68 ``abs(literal - constant) < DiffThreshold`` evaluates to ``true``. Default 69 is `0.001`. 70 71.. option:: IncludeStyle 72 73 A string specifying which include-style is used, `llvm` or `google`. Default 74 is `llvm`. 75