Significant Figures in C++

In this post, we will learn about significant figures in C++. Significant, as the name suggests means the number of digits that are actually meaningful to us. For example, the number 2544 has 4 significant figures. C++ supports many types of variables like int, float, char, etc. While using the data types like float and double our answer can have a large number of digits after the decimal point. For example 1/6=0.166666666. Moreover, sometimes we might get an answer that overflows the memory because we are provided with only 4 bytes or 8 bytes of memory depending upon the data type and the size allocated to it.

The number of significant figures is a measure of the precision of our answer. This means that when we say our answer has 4 significant figures, we are implying that our answer is precise up to 4 places. The data types follow a hierarchy with respect to the precision they give. Long double is the most precise and float is the least precise among float, double and long double. Typically, the float has 7 significant digits while double has 15 significant digits. Hence, while rounding off a number with more than 7 significant digits float has more error as compared to a double type number. We can set the precision of our answer in C++ according to our needs.

C++ has a library called iomanip which provides us a function named setprecision() using which we can change the number of significant digits.

Significant figures in C++ using setprecision()

#include <iostream>
#include<iomanip>
using namespace std;

int main() {
  float num=8.28478; //6 significant figures
  
  cout<<setprecision(1)<<num<<endl;   //1 significant figures
  cout<<setprecision(2)<<num<<endl;   //2 significant figures
  cout<<setprecision(3)<<num<<endl;   //3 significant figures
  cout<<setprecision(4)<<num<<endl;   //4 significant figures
  cout<<setprecision(5)<<num<<endl;   //5 significant figures
  cout<<setprecision(6)<<num<<endl;   //6 significant figures
  
  
  return 0;
}

OUTPUT

8
8.3
8.28
8.285
8.2848
8.28478

The output we are getting helps us to understand the working of the setprecision() function. When we want only 1 significant figure, our number is rounded off to 8 i.e a single digit. Next, if we want our answer to be precise up to 2 places, the number is rounded off to 8.3. In this way, we can manage the number of precise or significant digits we want in our answer.

READ MORE:
nearbyint() function in C++ with examples

Leave a Reply

Your email address will not be published. Required fields are marked *