在函数定义中使用特征库时,小数点不会按预期存储

Decimal points are not stored as expected when Eigen library is used in function definition

本文关键字:小数点 存储 定义 函数 特征      更新时间:2023-10-16

我正在使用特征库做一个C++程序,当我执行代码时,我的变量 P 为

`-4 -3 -2 -1 0 1 2 3 4 5`

但它应该是-4.5 -3.5-2.5-1.5-0.5 1.5 2.5 3.5 4.5数字四舍五入到最接近的整数,接近无穷大。请帮助我找到解决问题的方法。

#include<iostream>
#include<math.h>
#include<stdlib.h>
#include<eigen3/Eigen/Dense>
#include<eigen3/Eigen/Core>
using namespace Eigen;
using namespace std;
using Eigen::MatrixXd;
using Eigen::MatrixXf;
MatrixXf create_linear_array(int &N1 , double &dx)
{

int i;MatrixXf num(10,1);
    for(i=0;i<10;i++)
     num(i,0)=(float)(((i+1)-(N1+1)/2));
return num;
}
int main()
{
//---------------------INITIALISATION & DECLARATION------------------------------
    double dx=0.030;
    int N1=10;
    MatrixXf P;
    P=create_linear_array(N1,dx);
    cout<<P<<endl;
    return 0;

}

您正在执行整数除法,整数除法的结果始终是整数。只有之后你才将结果投射到浮点数上,但为时已晚。解决此问题的最简单方法是使用浮点文字2.0而不是2。这是有效的,因为2.0是双精度数,当您将整数除以双精度时,整数首先转换为双精度。

num(i,0)=(float)(((i+1)-(N1+1)/2.0));

@john已经指出了错误的原因。我只想指出,Eigen 中有一个内置函数LinSpaced用于您想要做的事情:

int N1=10;
MatrixXf P;  // consider using VectorXf here
float const limit = 0.5f*(N1-1);
P = VectorXf::LinSpaced(N1, -limit, +limit);