I am trying to add one vector to another vector in my C++ program and addition is coming out inexact.
This is the vector class (using cmath library):
class Vec{
float dir, mag;
public:
Vec(float dir, float mag){
this->dir = dir;
this->mag = mag;
}
float getX(){
return cos(dir)*mag;
}
Vec operator + (Vec v2){
float triangleX = cos(dir)*mag+cos(v2.dir)*v2.mag;
float triangleY = sin(dir)*mag+sin(v2.dir)*v2.mag;
return Vec(atan2(triangleY, triangleX), sqrt(pow(triangleX,2)+pow(triangleY,2)));
}
};
And this is the main function:
int main(){
Vec v1(0, 3); // 0º
Vec v2(3.14159265/2, 3); // 90º
Vec v3(3.14159265, 3); // 180º
std::cout.precision(15);
std::cout<<"v1: "<<v1.getX()<<std::endl;
std::cout<<"v1+v2: "<<(v1+v2).getX()<<std::endl;
std::cout<<"v1+v3: "<<(v1+v3).getX()<<std::endl;
return 0;
}
And this is the output:
v1: 3
v1+v2: 2.99999976158142
v1+v3: 1.98007097372034e-014
As you can see, the first output v1 is fine.
The second output is the addition of 0 degrees and 90 degrees (an angle that was not supposed to affect the x component), his x component is close to 3, but not exactly 3.
The third output is the addition of 2 opposite vectors with the same magnitude, it was supposed to be 0, but it is not what shows here.
What is causing these strange additions and how do I make them exact?