How to Implement Polynomial Operations in C++?

In summary: And after that I am stuck again. :unsure:In summary, the conversation discusses the creation of a class called QuadraticPolyonym that describes a polynomial of second degree. The class should have a constructor function that takes in three coefficients as arguments and a method that calculates the discriminant. It should also have a method that returns a dynamic array with the real roots of the polynomial and support for addition of polynomials using the + operator. The conversation also mentions creating two instances of the class, reading coefficients from input, and printing the roots of the polynomial.
  • #1
mathmari
Gold Member
MHB
5,049
7
Hey! :giggle:

I am looking at the following:

a) Create a class QuadraticPolyonym that describes a polynomial of second degree, i.e. of the form $P(x)=ax^2+bx+c, a\neq 0$.The coefficients have to be givenas arguments at the construction ofan instance of the class. Implement a method Discriminant that calculates the discriminant $D=b^2-4ac$.
b) Implement a method Roots that returns a dynamic array (std::vector) with the real roots of $p(x)=0$.
c) Support addition of polynomials with the operator $+$. With elements QuadraticPolyonym p1, p2; thepolynomial QuadraticPolyonym p3 = p1 + p2; should describe a polynomial where the coefficients isteh sum of the corresponding coefficients of the polynomials p1 and p2.
d) Write a program that creates two elements of the class QuadraticPolyonym P(x) and Q(x) reading the coefficinets from the input, adding these to get the polyomial R(x) and printing the roots of R(x)=0$ at the output.I have done the following :

Code:
#include <iostream>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>

using namespace std;

//Question(a)
class QuadraticPolyonym
{
private:
    double a, b, c;

public:

double Discriminant(double a, double b, double c) { return b*b-4*a*c; }

//Question (b)
double Roots(double a, double b, double c)
{
int x1, x2;
   if (Discriminant(a,b,c) > 0) {
        x1 = (-b + sqrt(Discriminant(a,b,c))) / (2*a);
        x2 = (-b - sqrt(Discriminant(a,b,c))) / (2*a);
        cout << "Roots are real and different." << endl;
        cout << "x1 = " << x1 << endl;
        cout << "x2 = " << x2 << endl;
    }

    else if (Discriminant(a,b,c) == 0) {
        cout << "Roots are real and same." << endl;
        x1 = -b/(2*a);
        cout << "x1 = x2 =" << x1 << endl;
    }

    else {
        cout << "Roots are complex"  << endl;
    }
    return 0;
}

//Question (c)
double* OperatorPlus(double x[3], double y[3])
{
double* z=new double[3];
int i;
    for( i = 0; i < 3; ++i) {
        z[i] = x[i] + y[i];
    }
    return z;
}};//Question (d)
int main()
{
QuadraticPolyonym R;
int i;
double coefP[3], coefQ[3],result[3];

cout<<"Enter the coefficients of P:\n";
for(i = 0; i < 3; i++) {
    cin>>coefP[i];
}
cout<<"Enter the coefficients of Q:\n";
for(i = 0; i < 3; i++){
    cin>>coefQ[i];
}

double* result = R.OperatorPlus(coefP, coefQ); //Question (c)

R.Roots(result[0],result[1], result[2]);

return 0;
}
It doesn't work as it should yet, but am I thinking in a correct way for the program? Or is this completely wrong? :unsure:
 
Last edited by a moderator:
Technology news on Phys.org
  • #2
Hey mathmari!

It says: The coefficients have to be given as arguments at the construction of an instance of the class.
That means there should be a constructor function named QuadraticPolyonym() with 3 parameters that initializes each of the 3 data members a, b, and c.
It should be used to construct p and q in main() like:
double a, b, c;
cin >> a >> b >> c;
QuadraticPolyonym p(a, b, c);
cin >> a >> b >> c;
QuadraticPolyonym q(a, b, c); 🤔

It says: Implement a method Discriminant.
That means there should be a method named Discriminant() without any parameters that should calculate the discriminant based on the 3 data members a, b, and c.
It should be called in main() like:
cout << "Discriminant P=" << P.Discriminant() << endl; 🤔

It says: Implement a method Roots that returns a dynamic array (std::vector).
That means there should be a method std::vector Roots(); without any parameters that returns an std::vector with the roots. 🤔

It says: Support addition of polynomials with the operator +.
That means there should be a global function QuadraticPolyonym operator+(const QuadraticPolyonym& p, const QuadraticPolyonym& q) that adds p and q together and returns the result.
It should be called in main() as specified in the problem. 🤔

It doesn't say how to read/print the polynomials for (d), so what you have in your main() is okay to read the coefficients.
But we should still construct the polynomials and use the methods we have to process them. 🤔
 
  • #3
Klaas van Aarsen said:
It says: The coefficients have to be given as arguments at the construction of an instance of the class.
That means there should be a constructor function named QuadraticPolyonym() with 3 parameters that initializes each of the 3 data members a, b, and c.
It should be used to construct p and q in main() like:
double a, b, c;
cin >> a >> b >> c;
QuadraticPolyonym p(a, b, c);
cin >> a >> b >> c;
QuadraticPolyonym q(a, b, c); 🤔

What exactly should this constructor function do? I got stuck right now. :unsure:
Klaas van Aarsen said:
It says: Implement a method Discriminant.
That means there should be a method named Discriminant() without any parameters that should calculate the discriminant based on the 3 data members a, b, and c.
It should be called in main() like:
cout << "Discriminant P=" << P.Discriminant() << endl; 🤔

Is the part in the class where I defined the discriminant wrong? ;unsure:
Klaas van Aarsen said:
It says: Implement a method Roots that returns a dynamic array (std::vector).
That means there should be a method std::vector Roots(); without any parameters that returns an std::vector with the roots. 🤔

Should it be :

Code:
std::vector Roots() 
{ 
int x1, x2; 
   if (Discriminant(a,b,c) > 0 || Discriminant() == 0) {
        x1 = (-b + sqrt(Discriminant())) / (2*a);
        x2 = (-b - sqrt(Discriminant())) / (2*a);
        return {x1,x2}
    }

    else {
        return 0;
    } 
}
:unsure:
 
  • #4
I changed now some things... Now I have:

Code:
#include <iostream> 
#include <string> 
#include <cstring> 
#include <cmath> 
#include <vector> 

using namespace std; class QuadraticPolyonym  
{ 
private: 
    double coef[3]; 

public: 
double Discriminant() {return b*b-4*a*c; } std::vector Roots() 
{ 
int x1, x2; 
   if (Discriminant() > 0 || Discriminant() == 0) {
        x1 = (-b + sqrt(Discriminant())) / (2*a);
        x2 = (-b - sqrt(Discriminant())) / (2*a);
        return {x1,x2}
    }

    else {
        return 0;
    } 
} 

double QuadraticPolyonym::getCoef( int k ) const
{
   if ( k <= 2 )
      return coef[k];
   else
      return 0.0;          
}

void QuadraticPolyonym::setCoef(int k, double value)
{
   coef[k] = value;
}//-- Definition of +
QuadraticPolyonym operator+(const QuadraticPolyonym & P, const QuadraticPolyonym & Q )
{
   double sum;
   QuadraticPolyonym R;
   
   for ( int i=degree; i >= 0; i-- )
   {
      sum = P.getCoef( i ) + Q.getCoef( i );
      if ( sum != 0.0 )               
         R.setCoef( i, sum );  
   }

   return R;
}

};   
int main() 
{  
QuadraticPolyonym P,Q,R; 
int i; 
double coefP[3], coefQ[3]; 

cout<<"Enter the coefficients of P:\n";
for(i = 0; i < 3; i++) {
    cin >> x; 
    P.setCoef(i,x); 
} cout<<"Enter the coefficients of Q:\n";
for(i = 0; i < 3; i++){
    cin >> x; 
    Q.setCoef(i,x); 
}  

R=operator+(&P, &Q); 
 
R.Roots(); 
return 0; 
}
I still get some errors. But is this now on the correct way? :unsure:
 
  • #5
You still don't have a constructor!

It's been a long time since I wrote C++. I prefer Pascal- but they aren't that different.

I think you need something like

class QuadraticPolynym
{
private
double a, b, c;

QuadraticPolynym(double p, double q, double r)
{ \\constructs the polynomial x^2
a= p; b= q; c= r;
}
 
  • #6
mathmari said:
I still get some errors. But is this now on the correct way? :unsure:

This QuadraticPolyonym exercise and the previous one about Matrix33 are about solving problems with Object Oriented Programming in C++.
That means learning about:
  • Classes
  • Constructors/destructors
  • Data members/member functions (aka methods)
  • public/protected/private access
  • operator overloading
To achieve that we need to solve the problems as is specified. (Sweating)

So for instance in (c) we need to have the code in main() that is like:
Code:
QuadraticPolyonym p1, p2;
QuadraticPolyonym p3 = p1 + p2;
That is to learn about operator overloading and we're supposed to figure out how to make it work. 🤔

The constructor of the class is written in the same way as it was for Matrix33, which Country Boy also highlighted.
Its purpose is to initialize a new instance of a class based on some parameters.
In this case the parameters of the public constructor must be copied to the private data members of the class. 🤔
 
Last edited:

FAQ: How to Implement Polynomial Operations in C++?

What is a polynomial in C++?

A polynomial in C++ is an algebraic expression consisting of one or more terms, where each term contains a variable raised to a non-negative integer power. These expressions can be used to represent mathematical equations, functions, and data in computer programs.

How do I declare a polynomial in C++?

To declare a polynomial in C++, you can use the class keyword to define a new data type, and then use variables to represent the coefficients and powers of the polynomial terms. Alternatively, you can use the struct keyword to define a structure that holds the coefficients and powers as members.

How do I perform addition or subtraction of polynomials in C++?

To perform addition or subtraction of polynomials in C++, you can use operator overloading to define the + and - operators for your polynomial class or structure. These operators should combine the like terms of the two polynomials and return a new polynomial as the result.

How do I multiply or divide polynomials in C++?

To multiply or divide polynomials in C++, you can use the * and / operators, which can also be overloaded for your polynomial class or structure. These operators should apply the distributive property and return a new polynomial as the result.

Can I use standard library functions to perform polynomial operations in C++?

Yes, the C++ standard library provides the std::valarray class, which allows you to perform arithmetic operations on arrays of values, including polynomials. Additionally, there are various third-party libraries and packages that offer more advanced polynomial operations for C++.

Similar threads

Replies
23
Views
2K
Replies
6
Views
10K
Replies
22
Views
3K
Replies
39
Views
4K
Replies
17
Views
2K
Replies
35
Views
3K
Back
Top