Listing 3: Function uncertain_print()
// prints uncertainty to 2 digits and value to same precision
inline void uncertain_print(double mean, double sigma, ostream &os = cout)
{
int original_precision = os.precision();
long original_format = os.flags(ios::showpoint);
int precision;
// special cases for zero, NaN, and Infinities
// (positive & negative)
if ((sigma == 0.0) || (sigma != sigma) || (1.0/sigma == 0.0))
{
precision = 0;
}
else
{
// round sigma to 2 digits
int sigma_digits = 1 - int(floor(log10(fabs(sigma))));
double round_10_pow = pow(10.0, sigma_digits);
sigma = floor(sigma * round_10_pow + 0.5) / round_10_pow;
// round mean to same # of digits
mean = floor(mean * round_10_pow + 0.5) / round_10_pow;
if (mean == 0.0)
{
if (sigma_digits > 0)
precision = sigma_digits + 1;
else
precision = 1;
}
else
{
precision = int(floor(log10(fabs(mean)))) + sigma_digits + 1;
if (precision < 1)
{
mean = 0.0;
if (sigma_digits > 0)
precision = sigma_digits + 1;
else
precision = 1;
}
}
}
os << setprecision(precision)
<< mean << " +/- "
<< setprecision(2)
<< sigma
<< setprecision(original_precision);
os.flags(original_format);
}
//End of File