std::numbers#
C++20 introduced mathematical constants via the
<numbers> header.
For example, we can compute the area of a circle, using the value of \(\pi\) from this library:
#include <iostream>
#include <numbers>
int main() {
double r{2.0};
// we'll compute r**2 as r * r
double area = std::numbers::pi * r * r;
std::cout << "area = " << area << std::endl;
}
Important
By default, the compilers we are using assume C++17 as the
standard. For access to the <numbers> library, we need to tell
the compiler to use the C++20 standard. We do this by adding
-std=c++20 to the compile line, e.g.:
g++ -std=c++20 -o circle circle.cpp