c++ - 用小数字代替零?

标签 c++ math double-precision

我一直在制作一个矩阵类(作为学习练习),我在测试我的反函数时遇到了问题。

我这样输入一个任意矩阵:

2 1 1
1 2 1
1 1 2

然后用它来计算倒数,我得到了正确的结果:

0.75 -0.25 -0.25
-0.25 0.75 -0.25
-0.25 -0.25 0.75

但是当我尝试将两者相乘以确保我得到单位矩阵时,我得到:

1 5.5111512e-017 0
0 1 0
-1.11022302e-0.16 0 1

为什么我会得到这些结果?我会理解,如果我乘以奇怪的数字,我可以理解一些舍入错误,但它所做的总和是:

2 * -0.25 + 1 * 0.75 + 1 * -0.25

这显然是 0,而不是 5.111512e-017

如果我手动获取它来进行计算;例如:

std::cout << (2 * -0.25 + 1 * 0.75 + 1 * -0.25) << "\n";

我按预期得到 0?

所有数字都表示为 double 。 这是我的乘法重载:

Matrix operator*(const Matrix& A, const Matrix& B)
{
    if(A.get_cols() == B.get_rows())
    {
        Matrix temp(A.get_rows(), B.get_cols());
        for(unsigned m = 0; m < temp.get_rows(); ++m)
        {
            for(unsigned n = 0; n < temp.get_cols(); ++n)
            {
                for(unsigned i = 0; i < temp.get_cols(); ++i)
                {
                    temp(m, n) += A(m, i) * B(i, n);
                }
            }
        }

        return temp;
    }

    throw std::runtime_error("Bad Matrix Multiplication");
}

和访问函数:

double& Matrix::operator()(unsigned r, unsigned c)
{
    return data[cols * r + c];
}

double Matrix::operator()(unsigned r, unsigned c) const
{
    return data[cols * r + c];
}

这是求逆的函数:

Matrix Inverse(Matrix& M)
{
    if(M.rows != M.cols)
    {
        throw std::runtime_error("Matrix is not square");
    }

    int r = 0;
    int c = 0;
    Matrix augment(M.rows, M.cols*2);
    augment.copy(M);

    for(r = 0; r < M.rows; ++r)
    {
        for(c = M.cols; c < M.cols * 2; ++c)
        {
            augment(r, c) = (r == (c - M.cols) ? 1.0 : 0.0);
        }
    }

    for(int R = 0; R < augment.rows; ++R)
    {
        double n = augment(R, R);
        for(c = 0; c < augment.cols; ++c)
        {
            augment(R, c) /= n;
        }

        for(r = 0; r < augment.rows; ++r)
        {
            if(r == R) { continue; }
            double a = augment(r, R);

            for(c = 0; c < augment.cols; ++c)
            {
                augment(r, c) -= a * augment(R, c);
            }
        }
    }

    Matrix inverse(M.rows, M.cols);
    for(r = 0; r < M.rows; ++r)
    {
        for(c = M.cols; c < M.cols * 2; ++c)
        {
            inverse(r, c - M.cols) = augment(r, c);
        }
    }

    return inverse;
}

最佳答案

关于c++ - 用小数字代替零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6230869/

相关文章:

c++ - 函数模板和迭代器

c++ - Boost chrono run_timer 未定义引用

c++ - 在 3d 空间中移动一个点

arrays - 有哪些方法可以查找包含特定实数值的数组元素?

c++ - OpenCV 显示像素值

c++ - 逐行读取文件的问题

c++ - 基于一个点的角度射击子弹

Javascript,b^2 和 b * b 不同

c - 如何翻译printf给出的%a的值?

MATLAB vpa() 不计算指数表达式的变量点数?