【问题标题】:Variable grouping providing different answers in optimized code变量分组在优化代码中提供不同的答案
【发布时间】:2014-02-01 09:26:57
【问题描述】:

我一直在尝试对我为大地变换编写的C++ 类进行单元测试。

我注意到三个变量的微小分组变化会极大地影响函数中的误差。

EDIT:这是一个可编译示例的整个函数:

假设latitude、longitude 和altitude 为零。 Earth::a = 6378137 和 Earth::b = 6356752.3 我正在努力获取基准数据,今天工作中出现了一些问题,我不得不这样做。

void Geodesy::Geocentric2EFG(double latitude, double longitude, double altitude, double *E, double *F, double *G) {
    double a2 = pow<double>(Earth::a, 2);
    double b2 = pow<double>(Earth::b, 2);
    double radius = sqrt((a2 * b2)/(a2 * pow<double>(sin(latitude), 2) + b2 * pow<double>(cos(longitude), 2)));
    radius += altitude;

    *E = radius * (cos(latitude) * cos(longitude));
    *F = radius * (cos(latitude) * sin(longitude));
    *G = radius * sin(latitude);

    return;
}

所有值都定义为double,包括Earth 中的值。 pow&lt;T&gt;() 函数是一个递归模板函数,定义如下:

template <typename T>
static inline T pow(const T &base, unsigned const exponent) {
     return (exponent == 0) ? 1 : (base * pow(base, exponent - 1));
}

有问题的代码:

*E = radius * cos(latitude) * cos(longitude);
*F = radius * cos(latitude) * sin(longitude);

产生不同的结果:

*E = radius * (cos(latitude) * cos(longitude));
*F = radius * (cos(latitude) * sin(longitude));

编译器在gcc 和优化级别3 中做了什么以使这些结果1e-2 不同?

【问题讨论】:

  • 使用汇编程序,卢克。为此尝试使用 gcc 资源管理器。 (请注意,我在这里没有为不同版本获得不同的汇编程序,但是 ymmv)
  • 在编译 w/o 优化时会得到不同的结果吗?如果 Radius 与 sin/cos 范围 [-1,1] 相比非常大,那么会出现不同的结果
  • 让我做一个基准,我会回复你们
  • 请给我们SSCCE!
  • 该代码仍然不符合 SSCCE 的条件。除此之外,请向我们提供您遇到此行为的输入。没有它,我们就没有机会复制它;我们只能猜测。

标签: c++ gcc optimization floating-point floating-accuracy


【解决方案1】:

你有不同的舍入,因为浮点不能代表所有数字:

a * b * c; 是 (a * b) * c,可能与 a * (b * c) 不同。

你可能也有类似的加法问题。

加法示例:

10e10f + 1.f == 10e10f

所以(1.f + 10e10f) - 10e10f == 10e10f - 10e10f == 0.f
而1.f + (10e10f - 10e10f) == 1.f - 0.f == 1.f.

【讨论】:

  • 这并不能解释报告的行为,除非报告 1e-2 差异的值很大(radius 必须很大)。在与正常值相乘时,浮点 (a*b)*c 精确地产生 a•b•(1+e0)•c•(1+e1) 对于一些最多为 1/2 ULP 的舍入误差 e0 和 e1(在舍入中到最近的模式),而a*(b*c) 对某些错误 e2 和 e3 产生精确的 a•(b•c•(1+e2))•(1+e3)。当 e0 和 e1 为 +1/2 ULP 并且 e2 和 e3 为 -1/2 ULP 时,它们之间的最大差异出现,并且差异不会是 1e-2,除非radius 很大。
  • 如果radius 是以米为单位的地球半径并且代码使用 32 位浮点数,则可能是这种情况。
  • 随着问题的更新,我们看到 radius 是 6378137 并且正在使用 double。有了这些,(a*b)*c 和 a*(b*c) 之间的差异并不能解释观察到的 1e-2 的错误。
猜你喜欢
  • 2021-04-14
  • 2012-08-04
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2018-12-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多