Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ significant figures

How can I do math involving significant figures in C++? I want this to work correct with measured data from chemistry and physics experiments. An example: 65 / 5 = 10. I would need to get rid of unneeded decimal places and replace some digits with 0s.

Thanks!

like image 329
joshim5 Avatar asked Feb 02 '23 23:02

joshim5


2 Answers

This should get you what you need:

std::cout.precision(x); // x would be the number of significant figures to output
like image 56
Rion Williams Avatar answered Feb 06 '23 14:02

Rion Williams


This may not be the most efficient way, but you can create a custom sig fig data type.

class SigFigFloat
{
  SigFigFloat(vector<short> digits, int decimalIndex, bool negative);
  SigFigFloat operator+(const SigFigFloat &value);
  SigFigFloat operator-(const SigFigFloat &value);
  //etc...


}

It can be a lot of work, but if you implement this right, it can be a really flexible way to represent and do calculations with sig figs.

like image 34
user434565 Avatar answered Feb 06 '23 16:02

user434565