Reputation: 79
I am doing a C++ program using Eigen library and when I executed my code I got my variable P as
`-4 -3 -2 -1 0 1 2 3 4 5`
But it should be -4.5 -3.5-2.5-1.5-0.5 1.5 2.5 3.5 4.5
The numbers are getting rounded to the nearest integers towards infinity.Please help me find a solution to my problem.
#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;
}
Upvotes: 0
Views: 431
Reputation: 18827
The cause of your error was already pointed out by @john. I just want to point out that there is a built-in function LinSpaced
in Eigen for what you want to do:
int N1=10;
MatrixXf P; // consider using VectorXf here
float const limit = 0.5f*(N1-1);
P = VectorXf::LinSpaced(N1, -limit, +limit);
Upvotes: 2
Reputation: 87932
You are doing integer division and the result of integer division is always an integer. Only afterwards do you cast the result to a float, but then it is too late. Simplest way to fix this is to use a floating point literal 2.0
instead of 2
. This works because 2.0
is a double and when you divide an integer by a double, the integer is converted to a double first.
num(i,0)=(float)(((i+1)-(N1+1)/2.0));
Upvotes: 3