C++ Library - <ratio>



The <ratio> library in C++ provides a convenient way to work with the rational numbers at compile time. It is used for defining and manipulating fractional values in terms of numerator and denominator. It is used in the scenarios where the fractional arithmetic needs to be calculated and optimized during the compilation phase, ensuring that there is no runtime overhead.

The <ratio> library is widely used in combination with other libraries such as <chrono> for handling time units. The commonly used C++ <ratio> functions are listed below.

Including <ratio> Header

To include the <ratio> header in your C++ program, you can use the following syntax.

 #include <ratio> 

Functions of <ratio> Header

Below is list of all functions from <ratio> header.

Arithmetic

The arithmetic refers to the ability to perform basic mathematical operations on compile-time. The commonly used C++ <ratio> arithmetic functions are listed below along with their description.

Sr.NoFunction & Description
1ratio_add

It is used to add two ratio objects.

2ratio_subtract

It is used to subtract two ratio objects.

3ratio_multiply

It is used to multiply two ratio objects.

4ratio_divide

It is used to divide two ratio objects.

Adding Two Ratios

In the following example, we are going to declare the two ratios and retrieving the output as the sum of the both ratios.

 #include <iostream> #include <ratio> int main() { using x1 = std::ratio < 2, 4 > ; using x2 = std::ratio < 1, 4 > ; using a = std::ratio_add < x1, x2 > ; std::cout << "Result : " << a::num << "/" << a::den << std::endl; return 0; } 

Output

Following is the output of the above code −

 Result : 3/4 

Comparison

The <ratio> library provides a way ro compare different std::ratio types at compile-time using the following comparison functions that are listed below along with their description.

Sr.NoFunction & Description
1ratio_equal

It is used to compare two ratio objects for equality.

2ratio_not_equal

It is used to compare two ratio objects for inequality.

3ratio_less

It is used to compare two ratio objects for less than.

4ratio_less_equal

It is used to compare two ratio objects for less than or equal.

5ratio_greater

It is used to compare two ratio objects for greater than.

6ratio_greater_equal

It is used to compare two ratio objects for greater than or equal.

Comparing Two Ratios

Consider the following example, where we are going to declare two ratios and comparing them.

 #include <iostream> #include <ratio> int main() { using a1 = std::ratio < 1, 3 > ; using a2 = std::ratio < 3, 9 > ; if (std::ratio_equal < a1, a2 > ::value) { std::cout << "Both Ratios are Equal" << std::endl; } else { std::cout << "Both Ratios are Not Equal" << std::endl; } return 0; } 

Output

Output of the above code is as follows −

 Both Ratios are Equal 
Advertisements
close