// // main.cpp // complex // // Created by Mark Brautigam on 11/21/16. // Copyright © 2016 Mark Brautigam. All rights reserved. // #include <iostream> #include <cmath> #include <assert.h> using namespace std; class Complex { private: double real, imag; // rectangular coordinates double mag, theta; // polar coordinates bool cartesian, polar; // which set is valid? void calculateCartesian(); void calculatePolar(); public: Complex(); Complex(double r, double i); double getReal(); double getImag(); double getMag(); double getTheta(); void printCartesian(); void printPolar(); void setPolar (double m, double t); }; void Complex::setPolar (double m, double t) { mag = m; theta = t; cartesian = false; polar = true; } void Complex::printCartesian() { cout << getReal() << " + " << getImag() << "i\n"; } void Complex::printPolar() { cout << getMag() << " e^ " << getTheta() << "i\n"; } void Complex::calculateCartesian() { assert(polar); real = mag * cos (theta); imag = mag * sin (theta); cartesian = true; } // not in textbook void Complex::calculatePolar() { assert (cartesian); mag = sqrt (real * real + imag * imag); theta = atan ( imag / real ); polar = true; } Complex::Complex () { cartesian = false; polar = false; } Complex::Complex (double r, double i) { real = r; imag = i; cartesian = true; polar = false; } double Complex::getReal() { if (cartesian == false) calculateCartesian(); return real; } // not in textbook double Complex::getImag() { if (cartesian == false) calculateCartesian(); return imag; } // not in textbook double Complex::getMag() { if (polar == false) calculatePolar(); return mag; } // not in textbook double Complex::getTheta() { if (polar == false) calculatePolar(); return theta; } Complex add (Complex a, Complex b) { double real = a.getReal() + b.getReal(); double imag = a.getImag() + b.getImag(); Complex sum (real, imag); return sum; } Complex multiply (Complex a, Complex b) { double mag = a.getMag() * b.getMag(); double theta = a.getTheta() + b.getTheta(); Complex product; product.setPolar (mag, theta); return product; } int main(int argc, const char * argv[]) { Complex c (2.0, 3.0); c.printCartesian(); c.printPolar(); Complex d (17.0, 42.0); Complex sum = add (c, d); sum.printCartesian(); Complex e (2, 2); Complex product = multiply (c, e); product.printCartesian(); Complex bad; bad.printCartesian(); cout << "I got this far!"; return 0; }
Monday, November 21, 2016
Complex Number Class
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment