Open In App

C++ 20 – <numbers> Header

C++20 has a recently developed header file labeled that incorporates mathematical functions and constants. Its purpose is to provide standard library support for mathematical operations, simplifying the process for C++ programmers to incorporate mathematical functions and constants into their programming. Our focus in this essay is the header file of C++20 and its numerous features.

Syntax:



#include <numbers>

Example 1:




// C++ Program to demonstrate the use of the <numbers>
// header.
#include <iostream>
#include <numbers>
  
int main()
{
    std::cout << "Pi: " << std::numbers::pi << std::endl;
    std::cout << "e: " << std::numbers::e << std::endl;
    std::cout << "Sqrt of 2: " << std::numbers::sqrt2
              << std::endl;
    return 0;
}

Output:



Pi: 3.14159
e: 2.71828
Sqrt of 2: 1.41421

Explanation: In this example, Within the header file, one can find a plethora of mathematical constants, such as pi, e, and the square root of 2. These constants are designated as inline variables within their corresponding types.

Example 2:




// C++ Program to demonstrate the use of the <numbers>
// header.
#include <cmath>
#include <iostream>
#include <numbers>
  
int main()
{
    std::cout << "sin(pi/6): "
              << std::sin(std::numbers::pi / 6)
              << std::endl;
    std::cout << "cosh(2): " << std::cosh(2) << std::endl;
    std::cout << "exp(1): " << std::exp(1) << std::endl;
    return 0;
}

Output:

sin(pi/6): 0.5
cosh(2): 3.7622
exp(1): 2.71828

Explanation: In this example, Templates are used in the header file to define a variety of mathematical functions, such as exponential functions, trigonometric functions, and hyperbolic functions. These functions are versatile and can be used for any type that supports the necessary operations.

Advantages of using <numbers> Header are:


Article Tags :
C++