Tuesday Coding Tip 15 — Mathematical constants in C++

2 5 31
calendar_todayschedule1 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
    */
}
Part 3 of 4 in Tuesday Coding Tips

1 Comment

0 votes
🔥 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
937 Points38 Badges
Brno, Czech Republiclinkedin.com/in/jakub-neruda
23Posts
10Comments
9Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!