Tuesday Coding Tip 15 — Mathematical constants in C++

2 5 25
calendar_today agoschedule1 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
    */
}
837 Points32 Badges2 5 25
Brno, Czech Republiclinkedin.com/in/jakub-neruda
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.
Part 3 of 3 in Tuesday Coding Tips
🔥 Join developers growing publicly
Share your knowledge, build in public, and grow your developer presence with a global community.

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Tuesday Coding Tip 05 - Object initialization in C++

Jakub Neruda - Mar 31

Tuesday Coding Tip 08 — Explicit template specialization

Jakub Neruda - Apr 21

Tuesday Coding Tip 01 - C++ Concepts

Jakub Neruda - Mar 3
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!