-
-
Save mariamyzz/d4a41b16ad11c636cb30dfbe17449e24 to your computer and use it in GitHub Desktop.
Gram-Shmidt orthogonalization for R3 basis problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
struct Vector { | |
Vector(double x, double y, double z) { | |
this->x = x; | |
this->y = y; | |
this->z = z; | |
} | |
Vector() : x(0), y(0), z(0) {} | |
double x, y, z; | |
double length() { | |
return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2)); | |
} | |
}; | |
// operator overloading for Vectors | |
Vector operator * (double alpha, Vector v) { | |
return Vector (alpha * v.x, alpha * v.y, alpha * v.z); | |
} | |
Vector operator * (Vector v, double alpha) { | |
return alpha * v; | |
} | |
double operator * (Vector v1, Vector v2) { | |
return (v1.x * v2.x + v1.y * v2.y + v1.z * v2.z); | |
} | |
Vector operator / (Vector v, double alpha) { | |
return Vector (v.x / alpha, v.y / alpha, v.z / alpha); | |
} | |
Vector operator - (Vector v1, Vector v2) { | |
return Vector (v1.x - v2.x, v1.y - v2.y, v1.z - v2.z); | |
} | |
Vector operator + (Vector v1, Vector v2) { | |
return Vector (v1.x + v2.x, v1.y + v2.y, v1.z + v2.z); | |
} | |
ostream & operator << (ostream & os, Vector v) { | |
os << "[" << v.x << ", " << v.y << ", " << v.z << "]"; | |
return os; | |
} | |
// extra functions for Vectors | |
Vector createVector() { | |
double x, y, z; | |
cout << "Define your vectors coordinates: "; | |
cin >> x >> y >> z; | |
return Vector(x, y, z); | |
} | |
/*Vector projection(Vector v1, Vector v2) { | |
}*/ | |
bool isOrthogonal(Vector v1, Vector v2) { | |
return abs(v1 * v2) < 0.0000005; | |
} | |
int main() | |
{ | |
// non-orthonormal basis vectors | |
Vector f1 = createVector(); | |
Vector f2 = createVector(); | |
Vector f3 = createVector(); | |
//orthogonalization | |
Vector e1(f1); | |
Vector e2 = (f2 - (e1 * (e1 * f2))/(e1 * e1)); | |
Vector e3 = ( f3 - ( ((f3 * e1) * e1)/(e1 * e1) ) - ( ( (f3 * e2) * e2 )/(e2 * e2) ) ); | |
//checking orthogonalization | |
cout << isOrthogonal(e1, e2) << endl; | |
cout << isOrthogonal(e2, e3) << endl; | |
cout << isOrthogonal(e1, e3) << endl; | |
// normalization | |
e1 = e1/e1.length(); | |
e2 = e2/e2.length(); | |
e3 = e3/e3.length(); | |
//checking if normalization worked | |
cout << e1.length() << " " << e2.length() << " " << e3.length() << endl; | |
//printing out the orthonormal vectors | |
cout << e1 << " " << e2 << " " << e3 << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment