简体   繁体   English

Eigen C ++将double转换为long int吗?

[英]Eigen c++ cast double to long int?

Quick question: 快速提问:

consider this (wrong) casting from a double to a long int: 考虑这种从双精度整数到长整数的(错误)转换:

Eigen::VectorXd Price      = Map<VectorXd>(price, n);
double TickFactor          = 1.0 / TickSize;
Eigen::VectorXi IntPrice   = (Price * TickFactor).cast <long int> ();

which gives the following error (Eigen 3.3.5, g++ 7.3.0): 这会产生以下错误(Eigen 3.3.5,g ++ 7.3.0):

eigen/Eigen/src/Core/util/StaticAssert.h:33:40: error: static assertion failed: YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY
     #define EIGEN_STATIC_ASSERT(X,MSG) static_assert(X,#MSG);

Now, this compiles: 现在,将编译:

Eigen::VectorXi IntPrice   = (Price * TickFactor).cast <int> ();

here is my question. 这是我的问题。 Does the line above allows for values of (Price * TickFactor) that are larger than the upper limit on a short int ? 上面的行是否允许(Price * TickFactor)值大于short int上限? --whatever that is on the current system, say 33K. -当前系统上的所有内容,例如33K。

This line 这条线

Eigen::VectorXi IntPrice   = (Price * TickFactor).cast <int> ();

is essentially equivalent to 基本上等于

Eigen::VectorXi IntPrice(Price.size());
for(Eigen::Index i=0; i<Price.size(); ++i)
    IntPrice[i] = static_cast<int>(Price[i] * TickFactor;

Unless on your system short int and int are the same, you are limited to the size of int (not short int ), and the behavior for overflows is (I think) undefined. 除非在您的系统上short intint相同,否则您将被限制为int的大小(而不是short int ),并且(我认为)溢出的行为是不确定的。

If you want 64bit integers, do as ggael suggested: 如果需要64位整数,请按照ggael的建议进行操作:

typedef Eigen::Matrix<int64_t,Dynamic,1> VectorXi64;

VectorXi64 IntPrice = (Price * TickFactor).cast<int64_t>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM