Poly* Poly::multiply(Poly* other) { double TOL = .00001; int n = getDegree(); int m = other->getDegree(); Poly* temp = new Poly(n + m); for (int i = 0; i <= n; i++) //loop over coeffs { for (int j = 0; j <= m; j++) //loop over second coeffs { double coeff_i = getCoeff(i); double coeff_j = other->getCoeff(j); if (fabs(coeff_i) > TOL && fabs(coeff_j) > TOL) { int power = i + j; double coeff = temp->getCoeff(power); temp->setCoeff(power, coeff + (coeff_i * coeff_j)); } } } return temp; }
Poly Poly::operator*(const Poly& p) { int newTerms = this->terms + p.terms - 1; Poly output = Poly(0, newTerms - 1); int c, t; //iterate over the outside array for (int i = 0; i < this->terms; i++) { if (this->coeffs[i] == 0) { continue; } //iterate over the inside array for (int j = 0; j < p.terms; j++) { if (p.coeffs[j] == 0) { continue; } //get values c = this->coeffs[i] * p.coeffs[j]; t = i + j; //assign values for new poly output.setCoeff(c, t); } } return output; }
int main() { Poly count[8]; cout << "Constructors" << endl; count[0] = Poly(); count[1] = Poly(1); count[2] = Poly(0); count[3] = Poly(-1); count[4] = Poly(0, 1); count[5] = Poly(1, 1); count[6] = Poly(-1, 1); count[7] = Poly(1, -1); for (int i = 0; i < 8; i++) { cout << count[i] << endl; } cout << "add" << endl; count[0].setCoeff(2,2); count[0].setCoeff(4,4); count[0].setCoeff(3,3); count[2].setCoeff(2,2); count[2].setCoeff(4,4); count[2].setCoeff(3,3); cout << count[0] << endl; cout << count[2] << endl; Poly p = count[0] + count[2]; cout << p << endl; p = p - count[0] - count[2]; cout << p << endl; p = p - count[0]; cout << p << endl; p.setCoeff(-1,-1); cout << p.getCoeff(-2) << endl; return 0; }
Poly Poly::operator+(const Poly& p) { //get maximum number of terms int newTerms = p.terms > this->terms ? p.terms : this->terms; //create output polynomial Poly output = Poly(0, newTerms - 1); //walk through coefficients for (int t = 0; t < newTerms; t++) { int c = 0; c += (t < this->terms) ? this->coeffs[t] : 0; c += (t < p.terms) ? p.coeffs[t] : 0; output.setCoeff(c, t); } return output; }
//assumes a specific format for the file //why is this method static in the header file? Poly* Poly::readPoly(const char* file_name) { ReadFile* rf = new ReadFile(file_name); //for reading String* degree_str = rf->readLine(); int degree = degree_str->a_to_i(); delete degree_str; Poly* poly = new Poly(degree); for (int i = 0; i <= degree; i++) { String* coeff_str = rf->readLine(); float coeff = coeff_str->a_to_f(); delete coeff_str; poly->setCoeff(i, (double) coeff); } delete rf; return poly; }