在函数定义中使用特征库时,小数点不会按预期存储
Decimal points are not stored as expected when Eigen library is used in function definition
我正在使用特征库做一个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);
相关文章:
- 将字符串存储在c++中的稳定内存中
- std::原子加载和存储都需要吗
- C++:将控制台输出存储在宏中更好吗
- 使用QProcess执行命令,并将结果存储在QStringList中
- 访问存储在向量C++中的结构的多态成员
- 如何从存储在std::映射中的std::集中删除元素
- 存储模板类型以强制转换回派生<T>
- 类型总是使用其大小存储在内存中吗
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 使用无符号字符数组有效存储内存
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 带结构的二维矢量:如何存储元素
- 添加存储在向量中的大整数的函数出现问题
- 用c++把小数点转换成八进制
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在std::vector上存储带有模板的类实例
- 谷歌测试中的期望值存储在哪里
- 为什么C中的通用链表中存储的数据已损坏
- 在函数定义中使用特征库时,小数点不会按预期存储