# Mathematical constants in C++20

published at 07.04.2021 14:36 by Jens Weller

Save to Instapaper Pocket

When I researched the library and language features of C++20 for the Meeting C++ Community survey, this one catched my eye.

And I thought its such a nice small feature, I should mention it on the blog. As all other C++20 blog posts right now seem to be about coroutines. It also is a nice follow up on an old blog of mine: C++ & π, where I showed the various ways of obtaining pi for C++ in 2013.

Now with C++20 there is support for pi in the standard with mathematical constants, residing in the namespace std::numbers:

inline constexpr double pi = pi_v<double>();

But wait there is more, alongside pi you also get inverse pi and inverse sqrt pi. The full list of supported constants:

- pi, inv_pi, inv_sqrtpi
- e ("Eulers number")
- log2e & log10e
- ln2 & ln10
- sqrt2 & sqrt3 + inv_sqrt3
- egamma (Euler Mascheroni constant)
- phi (golden ratio)

These are also provided as variable template (*_v, e.g. phi_v), the standard specializes these for float, double and long double. For a non standard type you could create your own specialization.

And together is this set of irrational numbers a great addition to the C++ Standard!

Join the Meeting C++ patreon community!

This and other posts on Meeting C++ are enabled by my supporters on patreon!