c++ - 计算数值误差

标签 c++ math linear-algebra numerical intel-mkl

如本 question 所示,MKL 给出的结果在串行执行和分布式执行之间存在差异。因此,我想研究那个错误。从我的书中我有:

|ε_(x_c)| = |x - x_c| <= 1/2 * 10^(-d) ,其中 d 指定在实际数字 x 和计算机拥有的数字 x_c 之间准确的十进制数字。

|ρ_(x_c)| = |x - x_c|/|x| <= 5 * 10^(-s)绝对相对误差,其中 s 指定有效位数。

所以,我们可以这样写代码:

double calc_error(double a,double x)
{
  return std::abs(x-a)/std::abs(a);
}

例如为了计算绝对误差,如here所示.

除了绝对误差和绝对相对误差之外,还有更多类型的误差需要研究吗?

以下是我可以使用的一些数据:

serial gives:
-250207683.634793 -1353198687.861288 2816966067.598196 -144344843844.616425 323890119928.788757
distributed gives:
-250207683.634692 -1353198687.861386 2816966067.598891 -144344843844.617096 323890119928.788757

然后我可以将想法扩展到实际数据和结果。

最佳答案

没有比绝对和绝对相对误差更复杂的了。还有另一种方法比较浮点格式的整数表示,这个想法是你希望你的“公差”适应你正在比较的数字的大小(特别是因为没有“尽可能多”的数字表示取决于量级)。

总而言之,我认为您的问题与浮点比较非常相似,其中有this excellent guide。 ,这更详尽但是much longer paper .

为了比较浮点值,可能还值得加入这些:

#include <limits>
#include <cmath>

template <class T>
struct fp_equal_strict
{
    inline bool operator() ( const T& a, const T& b )
    {
        return std::abs(a - b) 
            <= std::max(
                std::numeric_limits<T>::min() * std::min( std::abs(a), std::abs(b) ),
                std::numeric_limits<T>::epsilon()
            );
    }
};

template <class T>
struct fp_equal_loose
{
    inline bool operator() ( const T& a, const T& b )
    {
        return std::abs(a - b) 
            <= std::max(
                std::numeric_limits<T>::min() * std::max( std::abs(a), std::abs(b) ),
                std::numeric_limits<T>::epsilon()
            );
    }
};

template <class T>
struct fp_greater
{
    inline bool operator() ( const T& a, const T& b )
    {
        return (a - b) >= std::numeric_limits<T>::min() * std::max( std::abs(a), std::abs(b) );
    }
};

template <class T>
struct fp_lesser
{
    inline bool operator() ( const T& a, const T& b )
    {
        return (b - a) >= std::numeric_limits<T>::min() * std::max( std::abs(a), std::abs(b) );
    }
};

关于c++ - 计算数值误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078505/

相关文章:

c++ - 用于检测模板特化的模板元函数

algorithm - 估计下载时间的更好算法

c++ - 对 3X3 或 4X4 行列式进行单元测试

python - 使用python增加数组的维数

c++ - 逐字浏览文本文件并替换某些单词

c++ - 关于对抗逆变的问题。回调相关问题

c++ - 容器类型的通用 `erase_if` 方法

python - 如何在 python 中建立和求解联立方程

matlab - 理解Matlab linsolve

python - 像在 MATLAB 中一样在 Python 中连接矩阵/向量?