1

我有三组数字,一个测量值(在 0-1 范围内),两个错误(正数和负数)。这些数字应该与有效数字的数量一致,四舍五入,对应于第一个非任何一个数字中的零条目。

如果它是一个,则在测量中跳过此要求(即只需要考虑误差中的数字)。例如:

0.95637 (+0.00123, -0.02935) --> 0.96 +0.00 -0.03
1.00000 (+0.0, -0.0979) --> 1.0 +0.0 -0.1 (note had to truncate due to -ve error rounding up at first significant digit)

现在,通过取 log10(num) 很容易获得第一个非零数字,但我有一个愚蠢的时刻,试图让剥离和舍入以一种干净的方式工作。

所有数据类型都是双精度的,选择的语言是 C++。欢迎所有和任何想法!

4

5 回答 5

2

使用

cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);

在你输出数字之前应该做你正在寻找的东西。

编辑:例如

double a = 0.95637;
double b = 0.00123;
double c = -0.02935;

cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << a << endl;
cout << b << endl;
cout << c << endl;

将输出:

0.96
0.00
-0.03

进一步编辑:您显然必须调整精度以匹配您的有效数字。

于 2009-06-05T22:43:40.313 回答
2

我的 C++ 生锈了,但以下不会这样做:

std::string FormatNum(double measurement, double poserror, double negerror)
{
  int precision = 1;  // Precision to use if all numbers are zero

  if (poserror > 0)
    precision = ceil(-1 * log10(poserror));
  if (negerror < 0)
    precision = min(precision, ceil(-1 * log10(abs(negerror))));

  // If you meant the first non-zero in any of the 3 numbers, uncomment this:
  //if( measurement < 1 )
  //  precision = min(precision, ceil(-1 * log10(measurement)));

  stringstream ss;
  ss.setf(ios::fixed, ios::floatfield);
  ss.precision( precision );
  ss << measurement << " +" << poserror << " " << negerror ;
  return ss.str();
}
于 2009-06-05T22:58:15.010 回答
1

也许是这样的:

std::string FormatNum(double num)
{
  int numToDisplay ((int)((num + 0.005) * 100.0));
  stringstream ss;
  int digitsToDisplay(abs(numToDisplay) % 100);
  ss << ((num > 0) ? '+' : '-') << (abs(numToDisplay) / 100) << '.' << (digitsToDisplay / 10) << (digitsToDisplay % 10);
  return ss.str();
}

    stringstream ss;
    ss << FormatNum(0.95637) << ' ' << FormatNum(+0.00123) << ' ' << FormatNum(-0.02935);
于 2009-06-05T22:18:04.140 回答
0

我不太确定您的 log10 将如何帮助您获得第一个非零数字,但假设它确实如此(因此您知道要四舍五入的小数位),以下函数将正确四舍五入:

double round(double num, int decimalPlaces)
{
    //given your example of .95637 being rounded to two decimal places
    double decimalMultiplier = pow(10, decimalPlaces); // = 100
    double roundedShiftedNum = num * decimalMultiplier + 0.5; // = 96.137
    double insignificantDigits = (roundedShiftedNum - (int)roundedShiftedNum; // = 0.137
    return (roundedShiftedNum - insignificantDigits) / decimalMultiplier; // = (96.137 - 0.137)/100 = 0.96
}

这可能不是最优雅的解决方案,但我相信它有效(虽然没有尝试过)

于 2009-06-05T22:43:33.073 回答
0

这是Shane Powell提供的版本的变体。

std::string FormatNum(double num, int decimals)
{
    stringstream ss;
    if (num >= 0.0)
        ss << '+';
    ss << setiosflags(ios::fixed) << setprecision(decimals) << num;
    return ss.str();
}
于 2009-06-05T22:54:04.677 回答