Tuesday Coding Tip 15 — Mathematical constants in C++

●5 ●39 ●98
calendar_today • schedule1 min read
— Originally published at medium.com

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
    */
}

Want more #programming & #cpp deep dives?

Join 6,156+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 15 of 33 in Tuesday Coding Tips

1 Comment

0 votes

More Posts

Tuesday Coding Tip 33 — Imported CMake targets

Jakub Neruda - Dec 1

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Let's play with C++ reflection

Jakub Neruda - Nov 12

Tuesday Coding Tip 17 — Wrapping C APIs

Jakub Neruda - Jun 30
chevron_left
2.2k Points • 142 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
47Posts
40Comments
25Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

5 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!