特征:将向量除以标量可以分为两步,但不能一步一步

问题描述 投票:1回答:1

因此,我正在尝试实现Power iteration以找到C ++中的最大特征值和相应的特征向量。我正在使用本征库。奇怪的是,当我在一行中用标量将向量除以标量(在第(1)行中标记)时,它会引发错误,并且与C ++错误一样有用:

No viable conversion from 'typename internal::enable_if<true, const CwiseBinaryOp<internal::scalar_quotient_op<typename internal::traits<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0> >::Scalar, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>, const Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, const typename internal::plain_constant_type<Product<Product<Transpose<Matrix<double, -1, 1, 0, -1, 1> >, Matrix<double, -1, -1, 1, -1, -1>, 0>, Matrix<double, -1, 1, 0, -1, 1>, 0>, typename internal::promote_scalar_arg<Scalar, double, (Eigen::internal::has_ReturnType<Eigen::ScalarBinaryOpTraits<Scalar, double, Eigen::internal::scalar_quotient_op<Scalar, double> > >::value)>::type>::type> >::type'
(aka 'const Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<double, double>, const Eigen::Product<Eigen::Product<Eigen::Transpose<Eigen::Matrix<double, -1, 1, 0, -1, 1> >, Eigen::Matrix<double, -1, -1, 1, -1, -1>, 0>, Eigen::Matrix<double, -1, 1, 0, -1, 1>, 0>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<double>, const Eigen::Matrix<double, 1, 1, 0, 1, 1> > >')
to 'double'

但是当我分两步进行操作(在第(2)行中标记)时,一切都很好,并且不会引发任何错误。因此,我感到很奇怪,Eigen无法一步完成标量除法。这是怎么回事,为什么单行执行却失败?

pair<double, Vector> power_iteration(const Matrix& X, unsigned num_iter, double eps)
{
    Vector b = Vector::Random(X.cols());
    b.normalize();
    Vector b_old;
    for(unsigned int i = 0; i < num_iter; i++){
        b_old =b;
        b = X*b_old;
        b.normalize();
        double cos_angle = b.dot(b_old);
        if(cos_angle > 1-eps){
            i= num_iter+1;
        }
    }

   (1)  double eigenvalue = (b.transpose() * X * b)/(b.transpose().dot(b));

   (2)  double eigenvalue2 = b.transpose() * X * b;
    eigenvalue2 = eigenvalue2/b.transpose().dot(b);

    return make_pair(eigenvalue, b / b.norm());
}
c++ eigen
1个回答
0
投票

在(2)中,当您首先分配前一个表达式时,它会触发隐式转换为double,这是因为为其分配的变量是double。在(1)中,首先对前一个表达式进行评估,该表达式似乎是本征库定义的较高级别的类型,而后一个double表达式(点积)无法提升为该类型,因此错误。如果您明确告诉编译器您希望将b.transpose() * X * b减小为两倍,它将起作用:

double eigenvalue = static_cast<double>(b.transpose() * X * b)/(b.transpose().dot(b));
© www.soinside.com 2019 - 2024. All rights reserved.