Significant C ++ numbers

How can I do math with meaningful figures in C ++? I want this to work correctly with measured data from experiments in chemistry and physics. Example: 65/5 = 10. I need to get rid of unnecessary decimal places and replace some digits with 0.

Thanks!

+6
c ++ math rounding significant-digits
source share
6 answers

Ok, good math libraries in math.h

Also, saving your shapes in floats, doubles, or long doubles will allow you to perform more precise operations.

Floats offer 7 significant digits, and in doubles - 16 significant digits.

a source

In addition, when printing, people usually use _snprintf or printf, and you can format these doubles that float to the precision you need:

Float accuracy

printf ("Value% 8.2f", floatVariable);

This says that you need a total field of 8 characters, within 8 characters, the last 2 will contain the decimal part.

_snprintf (buffer, sizeof (buffer), "Value% .2f", floatVariable);

The example above asks for the minimum field width and the last two characters must be held to the decimal part.

-one
source share

This should get what you need:

std::cout.precision(x); // x would be the number of significant figures to output 
+6
source share

This may not be the most efficient way, but you can create your own 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 exercise this right, it can be a very flexible way to present and perform calculations using sig-figs.

+4
source share

This is difficult because meaningful numbers are a decimal concept, and computers are binary. You can use decimal number classes (I don't know anyone) or use boost :: interval , which is closest to what you definitely want to achieve.

+1
source share

It depends on how you show them. If you use the printf family, you set the precision ( sprintf(buffer, "%.2f", myfloat) ). If you use ostreams, you call the precision function to set the number of decimal places. If you are looking for a more scientific sig figs method, you will have to write a custom function that determines the accuracy based on the current float value.

+1
source share

here is a quick C ++ 11 solution that worked for me:

 int sig_figs = 3; double number = 1562.654478; std::cout << "original number:" << number << std::endl; number = ([number](int number_of_sig_figs)->double{ std::stringstream lStream; lStream << std::setprecision(number_of_sig_figs) << number; return std::stod(lStream.str()); })(sig_figs); std::cout << "rounded number:" << number << std::endl; 
0
source share

All Articles