- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Geometry using Complex Numbers in C++
In this section, we will see how to make point class using complex class from STL in C++. And apply them on some geometry related problems. The complex number is present inside the complex class from STL (#include <complex>)
Defining Point Class
To make complex to point, we will change the name of the complex<double> as point, then change x to real() of complex class and y to imag() of complex class. Thus, we can simulate the point class.
# include <complex> typedef complex<double> point; # define x real() # define y imag()
We have to keep in mind that the x and y have been applied as macros, these can’t be applied as variables.
Example
Let us see the following implementation to get better understanding −
#include <iostream> #include <complex> using namespace std; typedef complex<double> point; #define x real() #define y imag() int main() { point my_pt(4.0, 5.0); cout << "The point is :" << "(" << my_pt.x << ", " << my_pt.y << ")"; }
Output
The point is :(4, 5)
To apply geometry, we can find that the distance of P from origin (0, 0), this is denoted as −abs(P). The angle made by OP from axis X where O is the origin: arg(z). Rotation of P about origin is P * polar(r, θ).
Example
Let us see the following implementation to get better understanding −
#include <iostream> #include <complex> #define PI 3.1415 using namespace std; typedef complex<double> point; #define x real() #define y imag() void print_point(point my_pt){ cout << "(" << my_pt.x << ", " << my_pt.y << ")"; } int main() { point my_pt(6.0, 7.0); cout << "The point is:" ; print_point(my_pt); cout << endl; cout << "Distance of the point from origin:" << abs(my_pt) << endl; cout << "Tangent angle made by OP with X-axis: (" << arg(my_pt) << ") rad = (" << arg(my_pt)*(180/PI) << ")" << endl; point rot_point = my_pt * polar(1.0, PI/2); cout << "Point after rotating 90 degrees counter-clockwise, will be: "; print_point(rot_point); }
Output
The point is:(6, 7) Distance of the point from origin:9.21954 Tangent angle made by OP with X-axis: (0.86217) rad = (49.4002) Point after rotating 90 degrees counter-clockwise, will be: (-6.99972, 6.00032)