Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and LinkedIn.
Since C++20, you can include header <numbers> and use many commonly used, precomputed mathematical constants like Pi, Phi, square root of 2 and 3, natural logarithms of 2 and 10, and many more! Even better, you can choose their precision by specifying the underlying type via a template.
And since C++17, the <cmath> header contains some special math functions I’ve never heard of like cylindrical Bessel functions, associated Legendre polynomials, or Riemann zeta function.
#include <iostream>
#include <numbers>
#include <iomanip> // std::setprecision
#include <limits> // std::numeric_limits
template<typename T>
void printConstant(T value)
{
const auto default_precision{std::cout.precision()};
std::cout << std::setprecision(std::numeric_limits<T>::digits10 + 1);
std::cout << value << std::endl;
std::cout << std::setprecision(default_precision);
}
int main()
{
using namespace std::numbers;
printConstant(pi_v<float>);
printConstant(pi_v<double>);
printConstant(pi_v<long double>);
/* Outputs:
3.141593
3.141592653589793
3.141592653589793239
*/
}
19Posts
10Comments
9Followers
9Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.
✨ Build your own developer journey
Track progress. Share learning. Stay consistent.