11.18. Working with Polar Coordinates
Problem
You want to represent and manipulate polar coordinates.
Solution
The complex
template from the <complex> header
provides functions for conversion to and from polar coordinates. Example 11-34 shows how you can use the
complex template class to represent and manipulate polar coordinates.
Example 11-34. Using complex template class to represent polar coordinates
#include <complex>
#include <iostream>
using namespace std;
int main() {
double rho = 3.0; // magnitude
double theta = 3.141592 / 2; // angle
complex<double> coord = polar(rho, theta);
cout << "rho = " << abs(coord) << ", theta = " << arg(coord) << endl;
coord += polar(4.0, 0.0);
cout << "rho = " << abs(coord) << ", theta = " << arg(coord) << endl;
}Example 11-34 produces the following output:
rho = 3, theta = 1.5708 rho = 5, theta = 0.643501
Discussion
There is a natural relationship between polar coordinates and complex numbers. Even
though the two are somewhat interchangeable, it is generally not a good idea to use the
same type to represent different concepts. Since using the complex template to represent polar coordinates is inelegant, I have provided
a polar coordinate class that is more natural to use in Example 11-35.
Example 11-35. A polar coordinate class
#include <complex> #include <iostream> using namespace std; template<class T> struct BasicPolar { public: typedef BasicPolar self; // constructors BasicPolar() : m() { } BasicPolar(const self& x) : m(x.m) { } BasicPolar(const ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access