本征中的混合标量类型 [英] Mixing Scalar Types in Eigen

查看:99
本文介绍了本征中的混合标量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

#include <Eigen/Core>

namespace Eigen {

// float op double -> double
template <typename BinaryOp>
struct ScalarBinaryOpTraits<float, double, BinaryOp> {
  enum { Defined = 1 };
  typedef double ReturnType;
};

// double op float -> double
template <typename BinaryOp>
struct ScalarBinaryOpTraits<double, float, BinaryOp> {
  enum { Defined = 1 };
  typedef double ReturnType;
};

}

int main() {
    Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> m1(2, 2);
    m1 << 1, 2, 3, 4;

    Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> m2(2, 2);
    m2 << 1, 2, 3, 4;

    std::cerr << m1 * m2 <<std::endl;  // <- boom!!
}

我想知道为什么上面的代码无法编译。 此处是完整的错误消息。请注意,如果我将 m1 m2 定义为固定大小,则可以正常使用。

I'd like to know why the above code does not compile. Here is the full error messages. Please note that if I define m1 and m2 to have fixed sizes, it works fine.

我正在使用 Eigen3.3.1 。它已在运行OSX-10.12的Mac和苹果的<​​code> clang-800.0.42.1 上进行了测试。

I'm using Eigen3.3.1. It's tested on a Mac running OSX-10.12 with Apple's clang-800.0.42.1.

推荐答案

这是因为常规矩阵矩阵产品已通过积极的手动矢量化,流水线,多级缓存等进行了高度优化。该部分不支持浮点和双精度混合。您可以使用 m1.lazyProduct(m2)绕过这种高度优化的实现,该实现与用于小型固定大小矩阵的实现相对应,但是这样做的唯一缺点是: ALU不支持将float和double混合使用,因此无论如何都必须将float值提高为double,这样您就会失去向量化功能。最好将浮点数显式地加倍:

This is because the general matrix-matrix product is highly optimized with aggressive manual vectorization, pipelining, multi-level caching, etc. This part does not support mixing float and double. You can bypass this heavily optimized implementation with m1.lazyProduct(m2) that corresponds to the implementations used fro small fixed-size matrices, but there is only disadvantages of doing so: the ALUs does not support mixing float and double, so float values have to be promoted to double anyway and you will loose vectorization. Better cast the float to double explicitly:

m1.cast<double>() * m2

这篇关于本征中的混合标量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆