A polynomial class - c++

Here is the problem I am trying to solve:
Using dynamic arrays, implement a polynomial class with polynomial addition,
subtraction, and multiplication. Discussion: A variable in a polynomial does nothing but act as a placeholder for
the coefficients. Hence, the only interesting thing about polynomials is the array
of coefficients and the corresponding exponent. Think about the polynomial
xxx + x + 1
Where is the term in x*x ? One simple way to implement the polynomial class is to
use an array of doubles to store the coefficients. The index of the array is the
exponent of the corresponding term. If a term is missing, then it simply has a zero
coefficient.
There are techniques for representing polynomials of high degree with many missing
terms. These use so-called sparse matrix techniques. Unless you already know
these techniques, or learn very quickly, do not use these techniques.
Provide a default constructor, a copy constructor, and a parameterized constructor
that enables an arbitrary polynomial to be constructed.
Supply an overloaded operator = and a destructor.
Provide these operations:
polynomial + polynomial, constant + polynomial, polynomial + constant,
polynomial - polynomial, constant - polynomial, polynomial - constant.
polynomial * polynomial, constant * polynomial, polynomial * constant,
Supply functions to assign and extract coefficients, indexed by exponent.
Supply a function to evaluate the polynomial at a value of type double .
You should decide whether to implement these functions as members, friends, or standalone functions.
This is not for a class, I am just trying to teach myself C++ because I need it as I will start my graduate studies in financial mathematics at FSU this fall. Here is my code thus far:
class Polynomial
{
private:
double *coefficients; //this will be the array where we store the coefficients
int degree; //this is the degree of the polynomial (i.e. one less then the length of the array of coefficients)
public:
Polynomial(); //the default constructor to initialize a polynomial equal to 0
Polynomial(double coeffs[] , int nterms); //the constructor to initialize a polynomial with the given coefficient array and degree
Polynomial(Polynomial&); //the copy constructor
Polynomial(double); //the constructor to initialize a polynomial equal to the given constant
~Polynomial() { delete coefficients; } //the deconstructor to clear up the allocated memory
//the operations to define for the Polynomial class
Polynomial operator+(Polynomial p) const;
Polynomial operator-(Polynomial p) const;
Polynomial operator*(Polynomial p) const;
};
//This is the default constructor
Polynomial::Polynomial() {
degree = 0;
coefficients = new double[degree + 1];
coefficients[0] = 0;
}
//Initialize a polynomial with the given coefficient array and degree
Polynomial::Polynomial(double coeffs[], int nterms){
degree = nterms;
coefficients = new double[degree]; //array to hold coefficient values
for(int i = 0; i < degree; i++)
coefficients[i] = coeffs[i];
}
Polynomial::Polynomial(Polynomial&){
}
//The constructor to initialize a polynomial equal to the given constant
Polynomial::Polynomial(double){
}
Polynomial::operator *(Polynomial p) const{
}
Polynomial::operator +(Polynomial p) const{
}
Polynomial::operator -(Polynomial p) const{
}
I am just wondering if I am on the right track, if there is a better way of doing this please let me know. Any comments or suggestions would be greatly appreciated.

This is not a full answer but a starting point for you. I used std::set because it keeps its elements ordered, so I implemented a functor and used for my set. Now, elements in set will be sorted based on my comparison functor. In the current implementation, terms will be ordered in descending order in terms of exponents.
#include<set>
struct Term
{
int coefficient;
int exponent;
Term(int coef, int exp) : coefficient{ coef }, exponent{ exp } {}
};
struct TermComparator
{
bool operator()(const Term& lhs, const Term& rhs) {
return lhs.exponent < rhs.exponent;
}
};
class Polynomial
{
private:
std::set<Term, TermComparator> terms;
public:
Polynomial();
~Polynomial();
Polynomial operator+(Polynomial p);
};
My implementation allows you to store higher order polynomials efficiently.
I have implemented addition for you. It is not in best shape in terms OOP, but you can refactor it.
Polynomial Polynomial::operator+(Polynomial p)
{
auto my_it = terms.begin();
auto p_it = p.terms.begin();
Polynomial result;
while (my_it != terms.end() && p_it != p.terms.end())
{
if (my_it->exponent > p_it->exponent)
{
result.terms.insert(*my_it);
++my_it;
}
else if (my_it->exponent == p_it->exponent)
{
result.terms.insert(Term(my_it->coefficient + p_it->coefficient, my_it->exponent));
++my_it;
++p_it;
}
else
{
result.terms.insert(*p_it);
++p_it;
}
}
//only one of the for loops will be effective
for (; my_it != terms.end(); ++my_it) result.terms.insert(*my_it);
for (; p_it != p.terms.end(); ++p_it) result.terms.insert(*p_it);
return result;
}

State of your code
You code is correct so far if by nterms you mean maximum degree of your polynomial
One simple way to implement the polynomial class is to use an array of doubles to store the coefficients.
This is what you did
The index of the array is the exponent of the corresponding term
This is why I told you you array size is equal to the degree number + 1
This way you access the coefficient (the value of your array) using its degree (which will be the key)
If a term is missing, then it simply has a zero coefficient.
Notice that in the example given, x² doesn't exist, but coefficients[2] exists in your code and is equal to 0
Provide these operations: polynomial + polynomial, constant + polynomial, polynomial + constant, polynomial - polynomial, constant - polynomial, polynomial - constant. polynomial * polynomial, constant * polynomial, polynomial * constant, Supply functions to assign and extract coefficients, indexed by exponent. Supply a function to evaluate the polynomial at a value of type double
As you mentioned it, you are missing some of those operator overload.
To go further
Here's a non-exhaustive list of what could be done to get some more experience with C++ when you will be done with this exercise:
- You could implement an expression parser (using )
- Handle more complex polynomial (i.e. x² + y² + 2xy + 1)
- Use map to store your coefficients (Map may not be considered as dynamic arrays by this exercise but could be fun for you to play with) or another data structure to get ride of your zeros in your coefficients ! (c.f. sparse matrix/arrays techniques)
Have fun in your future studies !

Related

constructor for a polynomial class that must initialize the coefficients although the degree is unknown [duplicate]

This question already has answers here:
Variable number of arguments in C++?
(17 answers)
Closed 11 months ago.
i have this question:
You will implement a polynomial class that uses a dynamic array to store the polynomial's coefficients.
The Polynomial class has two private members variables: a dynamic array to store the
coefficients and the degree of the polynomial like so:
(private:
double *coef; // Pointer to the dynamic array
int degree; // the polynomial degree)
1.Write the constructors permitting the initialization of simple polynomials of the following way:
i. Polynomial p1(3,1); // polynomial of degree 1 p1 = 3 x+1
ii. Polynomial p2(1,4,2); // polynomial of degree 2 p2 = x2+4x+2
iii. Polynomial p3(1,3,3,1); // polynomial of degree 3 p3 = x3+ 3x2 + 3x +1
that is the question.
these constructors are being handed the coefficients but the number of coefficients is chosen by the user, how do i make such constructor(s)??
and i cant put a limit on the degree of the polynomial the user wants to enter(if this were the case, i could put default values that are zero so that if he doesnt give all coefficinets, the rest of coefficients will be zero)
is the dynamic array member going to help in this problem?
I suggest creating a struct Term:
struct Term
{
int coefficient;
int power;
};
A polynomial, by definition is a container (or sum) of terms:
class Polynomial
{
public:
std::vector<Term> terms;
Polynomial(int coef1, int constant1);
}
In the above class, the constructor will create two terms:
Polynomial::Polynomial(int coef1, int constant1)
{
Term t1;
Term c;
t1.coefficient = coef1;
t1.power = 1;
c.coefficient = constant1;
c.power = 0;
terms.push_back(c);
terms.push_back(t1);
}
The next constructor, in your requirements, creates 3 terms:
Polynomial::Polynomial(int coef1, int coef2, int constant1)
{
Term t1 = {coef1, 2};
Term t2 = {coef2, 1};
Term constant_term = {constant1, 0};
terms.push_back(constant_term);
terms.push_back(t2);
terms.push_back(t1);
}
One of the theorems of addition is that the terms can be in any order. You can change the order that you append them to the container so you print them in common order (highest exponent term first).
Array of Coefficients
In the requirements, there is double * coef which is supposed to be an array of coefficients (one for each term).
Here's one example of a constructor:
Polynomial::Polynomial(double coef1, double constant)
{
degree = 1;
coef = new double[2]; // 2 terms.
coef[0] = coef1;
coef[1] = constant;
}
The other constructors are similar to the above one.
Remember, your destructor should contain delete[] coef;.

C++: How to compute an integral with interval bounds?

I am both tired, new to C++ and real bad at dealing with polynomials. That's a bad combo for my assignment. Nevertheless I am trying to solve it. Please note that I might have misunderstood certain parts both mathematically and language-wise. Maybe even terminology.
The first task of my assignment was to create a class for storing polynomials. I figured the important parts were coefficiants and the degree of the polynomial. As such I have a polynomial class that (partly) looks like this:
class Polynomial {
private:
double* Coefficients; //Array of coefficients in order of ascending power
int Degree; //The degree of the polynomial
...
The class should have a method for finding the integral of the polynomial within a lower and upper bound. But I really do not know how to work with it.
Since it's bad practise not to show what I've done, this is what I currently have, and it probably does not make a lot of sense, but please, if you can, point me in the right direction?
Polynomial Polynomial::ComputeIntegral(double lower, double upper) {
//Values needed to create new polynomial
//degree will be one more than the original polynomial
int degree = Degree + 1;
double* coefficients = new double[degree + 1];
coefficients[0] = 0;
for (int i = 0; i < degree +1; i++) {
coefficients[i + 1] = Coefficients[i] / (double)(i + 1);
}
Polynomial integral(degree, coefficients);
return integral;
}
That I can see myself, it is messed up because a) I do not use the bounds, and b) I am pretty sure per the assignment description I should end up with a value rather than a new polynomial.
Google tells me there are algorithms to deal with finding integrals (Trapezoid for example), but I can not wrap my head around matching that with my representation of a polynomial.
A few pointers:
Use std::vectors instead of pointers and new. (If you are new to C++, there are very few circumstances when you actually need to use new.)
ComputeIntegral(double, double) will need to return a double, since it is obviously computing a definite integral. (The function you have at the moment would be something like GetPrimitive(), as it returns the primitive of the polynomial, which is another poly.
The definite integral is the difference of the primitive evaluated at the bounds (First Fundamental theorem of calculus).
There are a number of ways you could represent the polynomial as a data structure, but I would suggest a single std::vector<double> coeffs that represents all of the coefficients up to the degree of the poly, then the degree can be calculated at coeffs.size(). In some cases there may be zeroes in that coeffs though.
In the general case, it is possible to use the boost library to compute integrals: https://www.boost.org/doc/libs/1_77_0/libs/math/doc/html/quadrature.html
There is also the library ALGLIB that I have used to compute integrals. Here is an example to compute integrals with ALGLIB: Integrate a public but non static member function with ALGLIB

how to struct initializer and deque

So i have..
struct Polynomial{
deque<long> coefs;
long degree;
Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);
Polynomial();
string poly_to_string();
Polynomial add(Polynomial rhs);
Polynomial mult(Polynomial rhs);
Polynomial mult(long factor);
}
For theese methods I have to :
Polynomial(initializer_list cfs ). Initialize the instance using an initializer list of coefficients.
-order is the highest power goes first, lowest last
-coefs and degree updated.
Polynomial(deque cfs). Initialize the instance using a vector of coefficients. -order is the highest power goes first, lowest last
-coefs and degree updated.
Then I do methods to add/multiple/factor the polynomial, which I can do, just not sure what
Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);
are suppose to do / how to start them..
Also, how would i would I start the function to return
Polynomial.degree
To return a long value?
Those two functions are the constructors for the type. They tell the compiler how to set up a Polynomial object so that it's ready for members to be called. They're most easily understood like this:
struct Polynomial{
deque<long> coefs;
long degree;
Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);
};
Polynomial::Polynomial(initializer_list<long> co_list)
{
//at this point, the members are created, but have no values
//so we assign values to the members
coefs.assign(co_list.begin(), co_list.end());
degree = co_list.size();
}
int main()
{
Polynomial mypoly = {3, 4, 5};
//creates a Polynomial variable from an initializer list
//the compiler runs the constructor function automatically
//so now it's members are all properly set, and we can run other functions
mypoly.do_thing();
}
However, as shown above, the Polynomial constructor constructs the two members, and then executes the function that assigns them values. We can make this even better by constructing them directly with the intended values:
Polynomial::Polynomial(initializer_list<long> co_list)
:
coefs(co_list.begin(), co_list.end()), //constructed directly
degree(co_list.size())
{
//they already have the needed values, don't need to do anything more
//to finalize the construction
}

Core Dumped While Multiplying Iteratively

I am trying to do something very simple. I have a class for functions, and a class for polynomials derived from the function class. In the polynomial, I am overloading the *= operator. But, when I invoke this operator, the program dumps the core and crashes.
Polynomial& Polynomial::operator*= (double c)
{
for(int i = 0; i <= degree; i++)
a[i] = a[i] * c;
return *this;
}
The polynomial class holds the coefficients in array a. The index of a directly relates to the power of x for that particular coefficient. Function main hands us the constant c, which we then multiply each coefficient by.
The prototype for the function is part of an assignment, or I would change it. I'm assuming there's something I'm doing wrong with respect to the return type. Any help is appreciated.
I am willing to provide more code if requested.
The return type is fine, I'm guessing the problem is i <= degree instead of i < degree. Arrays in C++ are 0-based.
EDIT: or perhaps you want to keep that as <= for consistency with the polynomial, in which case you need to allocate degree+1 items for your array.

What does this structure actually do?

I found this structure code in a Julia Set example from a book on CUDA. I'm a newbie C programmer and cannot get my head around what it's doing, nor have I found the right thing to read on the web to clear it up. Here's the structure:
struct cuComplex {
float r;
float i;
cuComplex( float a, float b ) : r(a), i(b) {}
float magnitude2( void ) { return r * r + i * i; }
cuComplex operator*(const cuComplex& a) {
return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);
}
cuComplex operator+(const cuComplex& a) {
return cuComplex(r+a.r, i+a.i);
}
};
and it's called very simply like this:
cuComplex c(-0.8, 0.156);
cuComplex a(jx, jy);
int i = 0;
for (i=0; i<200; i++) {
a = a * a + c;
if (a.magnitude2() > 1000)
return 0;
}
return 1;
So, the code did what? Defined something of structure type 'cuComplex' giving the real and imaginary parts of a number. (-0.8 & 0.156) What is getting returned? (Or placed in the structure?) How do I work through the logic of the operator stuff in the struct to understand what is actually calculated and held there?
I think that it's probably doing recursive calls back into the stucture
float magnitude2 (void) { return return r * r + i * i; }
probably calls the '*' operator for r and again for i, and then the results of those two operations call the '+' operator? Is this correct and what gets returned at each step?
Just plain confused.
Thanks!
r and i are members of the struct declared as float. The expression in the magnitude2 function simply does standard float arithmetic with the values stored in those members.
The operator functions defined in the struct are used when the operators * and + are applied to variable of the struct type, for instance in the line a = a * a + c.
It's a C++ implementation of a complex number, providing a method to return the magnitude and operator overloads for addition and multiplication. The real (r) and imaginary (i) parts are stored separately.
a * a + c calls the overloaded methods: (a.operator*(a)).operator+(c)
It appears you have very little grasp of even C syntax (return r * r + i * i; returns r times r plus i times i), so I suggest you read a beginner's introduction to C/C++, followed by an introduction to complex numbers and then read up on operator overloading in C++.
This is not a simple struct but a class ( which is basically a struct with functions ) and is C++.
cuComplex c(-0.8, 0.156);
Here he creates an instance of this class and sets the 2 values by calling the constructor ( special function that initializes the instance fields of the class ).
This probably won't make enough sense so I suggest you study a C++ book. Accelerated C++ is a good choice if you already know some programming.
The multiplication operator simply takes the real and imaginary part of argument a and add these with the real and imaginary parts of the object the operator is called upon and returns a new complex number object of the result. I've added the this pointer to clarify:
cuComplex operator*(const cuComplex& a) {
// first constructor argument is the real part, second is the imaginary part
return cuComplex(this->r*a.r - this->i*a.i, this->i*a.r + this->r*a.i);
}
Same goes for the addition operator. Again the copy of a new object of type cuComplex is created and returned. This time the real and imaginary part of it being the sum of the respective fields of this object and the argument.
cuComplex operator+(const cuComplex& a) {
return cuComplex(this->r+a.r, this->i+a.i);
}
For the loop, it seems the imaginary number a is multiplied with itself (resulting in a rotation in the Re-Im-plane and and a constant imaginary c is added in each iteration until the magnitude (lenght) of the result exceeds a certain threshold.
Note that both the operator* and operator+, as well the function magnitude2() are members of structure cuComplex and thus the this pointer is available.
Hope that helps.
Like you said cuComplex hold two values for real (r) and imaginary (i) part of a number.
The constructor simply assigns the value to r and i.
The * operator are working on cuComplex numbers. The multiply and add operators will only be called if you multiply two cuComplex isntances together.
They are simply there to simplify you code. Without the operator you would have to do the add operation yourself:
cuComplex c(-0.8, 0.156);
cuComplex a(jx, jy);
// Add, both operations are equivalent.
cuComplex result1 = cuComplex(c.r + a.r, c.i + a.i);
cuComplex result2 = c + a;
As for the code
cuComplex c(-0.8, 0.156); // Create cuComplex instance called c
cuComplex a(jx, jy); // Create cuComplex instance called a
int i = 0;
for (i=0; i<200; i++) {
a = a * a + c; // Use the * and + operator of cuComplex
if (a.magnitude2() > 1000)
return 0;
}
return 1;
I think that it's probably doing
recursive calls back into the stucture
float magnitude2 (void) { return return r * r + i * i; }
It is not since r and i are float. The * and + operator are overloaded for cuComplex not float
You should tag this question as C++, not C (even if you have a struct, this one has a constructor and redefines operators which are typical object-oriented concepts).
This structure defines complex numbers, allows to multiply (via operator*), add them (via operator+) and get their module (via magnitude2).
At the beininning; you have one constant complex number, c, and a, another complex number which is not constant, given by user probably via coordinates jx and jy. At each iteration of the loop, a is mutliplied by itself and c is added to this result.
If at some point a has got a module greater than 1000, the loop ends. I guess this is a test program to see how the module of a grows according to initial conditions given by a user.
If you are familiar with the concept of classes replace the word "struct" with "class" it makes it much easier to understand.
The "class" contains two variables r and i, a constructor that takes two float args, an operator to multiply, an operator to add, and a function to calculate the magnitude.
In C++ simply use std::complex<float>.