C++ significant figures

孤街浪徒 提交于 2019-12-03 13:42:38

Well there are good math libraries in math.h

Also storing your figures in floats, doubles or long doubles will allow for more precise operations.

Floats offer 7 significant digits while doubles offer 16 significant digits.

source

Also when printing out usually people use _snprintf or printf and you can format those doubles, floats to the precision you want like:

Float Precision

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

This says you require a total field of 8 characters, within the 8 characters the last 2 will hold the decimal part.

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

The example above requests the minimum field width and the last two characters are to hold the decimal part.

This should get you what you need:

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

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.

It is hard because significant figures are a decimal concept, and computers speak binary. You can use decimal number classes (I don't know of any), or use boost::interval, which is the closest to what you certainly want to achieve.

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

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;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!