Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement Class \"polynomial\" with a Linked List I already wrote a program but

ID: 3839849 • Letter: I

Question

Implement Class "polynomial" with a Linked List
I already wrote a program but it is failing all the tests HELP PLEASE

I mostly need help with assign_coef and add_to_coef

LINKED LISTS

// FILE: poly2.h

// CLASS PROVIDED:

//   class polynomial (in the namespace main_savitch_5)

//     A polynomial has one variable x, real number coefficients, and

//     non-negative integer exponents. Such a polynomial can be viewed

//     as having the form:

//       A[n]*x^n + A[n-1]*x^(n-1) + ... A[2]*x^2 + A[1]*x + A[0]

//     where the A[n] are the real number coefficients and x^i represents

//     the variable x raised to the i power. The coefficient A[0] is

//     called the "constant" or "zeroth" term of the polynomial.

//  

// NOTES TO STUDENT:

//   1. This version works by storing the coefficients in

//      a doubly-linked list with each node holding the coefficient and

//      exponent for one term. The terms are kept in order from smallest

//      to largest exponent. Each polynomial also maintains a pointer to the

//      most recently accessed node.

//   2. Note that two functions have been implemented as inline functions

//      in this file (the degree and operator() functions).

//

// CONSTRUCTOR for the polynomial class

//     POSTCONDITION: This polynomial has been created with all zero

//     coefficients, except for coefficient c for the specified exponent.

//     When used as a default constructor (using default values for

//     both arguments), the result is a polynomial with all zero

//     coefficients.

//

// MODIFICATION MEMBER FUNCTIONS for the polynomial class

//   void add_to_coef(double amount, unsigned int exponent)

//     POSTCONDITION: Adds the given amount to the coefficient of the

//     specified exponent.

//

//   void assign_coef(double coefficient, unsigned int exponent)

//     POSTCONDITION: Sets the coefficient for the specified exponent.

//

//   void clear( )

//     POSTCONDITION: All coefficients of this polynomial are set to zero.

//

// CONSTANT MEMBER FUNCTIONS for the polynomial class

//   double coefficient(unsigned int exponent) const

//     POSTCONDITION: Returns coefficient at specified exponent of this

//     polynomial.

//

//   unsigned int degree( ) const

//     POSTCONDITION: The function returns the value of the largest exponent

//     with a non-zero coefficient.

//     If all coefficients are zero, then the function returns zero.

//

//   polynomial derivative( ) const

//     POSTCONDITION: The return value is the first derivative of this

//     polynomial.

//

//   double eval(double x) const

//     POSTCONDITION: The return value is the value of this polynomial with the

//     given value for the variable x.

//

//   void find_root(

//     double& answer,

//     bool& success,

//     unsigned int& iterations,

//     double starting_guess = 0,

//     unsigned int maximum_iterations = 100,

//     double epsilon = 1e-8

//     )

//     const

//     PRECONDITION: epsilon > 0.

//     POSTCONDITION: This function uses Newton's method to search for a root

//     of the polynomial (i.e., a value of x for which the polynomial is zero).

//     The method requires some starting guess for the value of the root. This

//     guess is improved over a series of iterations (with the maximum allowed

//     iterations defined by the parameter maximum_iterations). There are three

//     possible outcomes:

//     1. SUCCESS:

//        The method hits a near-root (a value of x for which the absolute

//        value of the polynomial is no more than epsilon). In this case, the

//        function sets answer to equal this near-root, success is set to true,

//        and iterations is set to the number of iterations required.

//     2. FLAT FAILURE:

//        Newton's method fails because the guess hits a very flat area of the

//        polynomial (a point where first derivative is no more than epsilon).

//        In this case, the function sets answer equal to the guess that caused

//        flat failure, success is set to false, and iterations is the number

//        of iterations carried out (which will be less than

//        maximum_iterations).

//     3. MAXIMUM ITERATIONS REACHED:

//        The maximum number of iterations is reached without success or flat

//        failure. In this case, the function sets answer to the last guess

//        tried, success is set to false, and iterations is set to

//        maximum_iterations.

//

//   unsigned int next_term(unsigned int e) const

//     POSTCONDITION: The return value is the next exponent n which is LARGER

//     than e such that coefficient(n) != 0.

//     If there is no such term, then the return value is zero.

//

//   unsigned int previous_term(unsigned int e) const

//     POSTCONDITION: The return value is the next exponent n which is SMALLER

//     than e such that coefficient(n) != 0.

//     If there is no such term, then the return value is UINT_MAX

//     from .

//

// CONSTANT OPERATORS for the polynomial class

//   double operator( ) (double x) const

//     Same as the eval member function.

//

// NON-MEMBER BINARY OPERATORS for the polynomial Class

//   polynomial operator -(const polynomial& p1, const polynomial& p2)

//     POSTCONDITION: return-value is a polynomial with each coefficient

//     equal to the difference of the coefficients of p1 & p2 for any given

//     exponent.

//

//   polynomial operator +(const polynomial& p1, const polynomial& p2)

//     POSTCONDITION: return-value is a polynomial with each coefficient

//     equal to the sum of the coefficients of p1 & p2 for any given

//     exponent.

//

//   polynomial operator *(const polynomial& p1, const polynomial& p2)

//     POSTCONDITION: Each term of p1 has been multiplied by each term of p2,

//     and the answer is the sum of all these term-by-term products.

//     For example, if p1 is 2x^2 + 3x + 4 and p2 is 5x^2 - 1x + 7, then the

//     return value is 10x^4 + 13x^3 + 31x^2 + 17x + 28.

//

// NON-MEMBER OUTPUT FUNCTION for the polynomial Class

//   ostream& operator << (ostream& out, const polynomial& p)

//     POSTCONDITION: The polynomial has been printed to ostream out, which,

//     in turn, has been returned to the calling function.

//     [CS 24 Note - std::endl is printed following the polynomial]

//

// DYNAMIC MEMORY

//   Since this class uses dynamic memory, the copy constructor and assignment

//   operator are overridden, and there is a destructor implemented. Also,

//   if there is insufficient dynamic memory, the following functions throw

//   a bad_alloc exception: the constructors, assignment, reserve, add_to_coef,

//   assign_coef, and any function that returns a polynomial.

#ifndef POLY2_H

#define POLY2_H

#include    // Provides NULL

#include // Provides ostream

namespace main_savitch_5

{

    // a node class for internal use - not part of polynomial interface

    class polynode

    {

    public:

        // CONSTRUCTOR: Creates a node containing a specified initial

        // coefficient (init_coef), initial exponent (init_exponent), and

        // initial links forward and backward (init_fore and init_back).

        polynode(

            double init_coef = 0.0,

            unsigned int init_exponent = 0,

            polynode* init_fore = NULL,

            polynode* init_back = NULL

            )

            {

                coef_field = init_coef;

                exponent_field = init_exponent;

                link_fore = init_fore;

                link_back = init_back;

            }

        // Member functions to set the fields:

            void set_coef(double new_coef)

            { coef_field = new_coef; }

            void set_exponent(unsigned int new_exponent)

            { exponent_field = new_exponent; }

            void set_fore(polynode* new_fore)

            { link_fore = new_fore; }

            void set_back(polynode* new_back)

            { link_back = new_back; }

        // Const member functions to retrieve current coefficient or exponent:

        double coef( ) const { return coef_field; }

        unsigned int exponent( ) const { return exponent_field; }

        // Two slightly different member functions to retrieve each link:

        const polynode* fore( ) const { return link_fore; }

            polynode* fore( )             { return link_fore; }

        const polynode* back( ) const { return link_back; }

            polynode* back( )             { return link_back; }

       

    private:

        double coef_field;

        unsigned int exponent_field;

        polynode *link_fore;

        polynode *link_back;

    };

    class polynomial

    {

    public:

            // CONSTRUCTORS and DESTRUCTOR

        polynomial(double c = 0.0, unsigned int exponent = 0);

        polynomial(const polynomial& source);

        ~polynomial( );

        // MODIFICATION MEMBER FUNCTIONS

        polynomial& operator =(const polynomial& source);

        void add_to_coef(double amount, unsigned int exponent);

        void assign_coef(double coefficient, unsigned int exponent);

        void clear( );

       

        // CONSTANT MEMBER FUNCTIONS

        double coefficient(unsigned int exponent) const;

        unsigned int degree( ) const { return current_degree; }

        polynomial derivative( ) const;

        double eval(double x) const;

        void find_root(

            double& answer,

            bool& success,

            unsigned int& iterations,

            double guess = 0,

            unsigned int maximum_iterations = 100,

            double epsilon = 1e-8

            )

            const;

        unsigned int next_term(unsigned int e) const;

        unsigned int previous_term(unsigned int e) const;

       

        // CONSTANT OPERATORS

        double operator( ) (double x) const { return eval(x); }

       

    private:

        polynode *head_ptr;             // Head pointer for list of terms

        polynode *tail_ptr;             // Tail pointer for list of terms

        mutable polynode *recent_ptr;   // Most recently used term

        unsigned int current_degree;    // Current degree of the polynomial

        // A private member function to aid the other functions:

        void set_recent(unsigned int exponent) const;

        // Set recent_ptr to the node that contains the requested exponent

        // If requested exponent is 0, then set recent_ptr to head of list

        // If exponent >= current degree, set recent_ptr to tail of list

        // If exponent < exponent in recent node, move recent_ptr backward as far as needed

        // Else move recent_ptr forward as far as needed

    };

   

    // NON-MEMBER BINARY OPERATORS

    polynomial operator +(const polynomial& p1, const polynomial& p2);

    polynomial operator -(const polynomial& p1, const polynomial& p2);

    polynomial operator *(const polynomial& p1, const polynomial& p2);

   

    // NON-MEMBER OUTPUT FUNCTION

    std::ostream& operator << (std::ostream& out, const polynomial& p);

}

#endif

Test code:

// FILE: polytest2.cxx

// An Interactive test program for the polynomial ADT

#include           // Provides toupper

#include         // Provides cout and cin

#include          // Provides EXIT_SUCCESS

#include "poly2.h"         // Provides the polynomial class

using namespace std;

using namespace main_savitch_5;

const unsigned int MANY = 3; // Number of polynomials allowed in this test program.

// PROTOTYPES for functions used by this test program:

void print_menu();

// Postcondition: The menu has been written to cout.

size_t set_current( );

// Postcondition: Return value is index for a new current polynomial.

char get_command();

// Postcondition: The user has been prompted for a character.

// The entered charatcer will be returned, translated to upper case.

void view(const polynomial& test);

//Postcondition: The polynomial passed has been sent to cout.

void view_all(const polynomial a[]);

//Postcondition: All polynomials has been written to cout.

void test_add(polynomial& test);

// Postcondition: The user has been prompted for a coefficent and degree of

// the term added. The resulting polynomial has been written to cout.

void test_assign(polynomial& test);

// Postcondition: The user has been prompted for the degree and the coeffinient

// to be set. The resulting polynomial has been written to cout.

void test_clear(polynomial& test);

// Postcondition: test.clear( ) has been activated.

// to be set. The resulting polynomial has been written to cout.

void test_eval(const polynomial& test);

// Post conditon: The user has been prompted for the x value. The evaluation

// of the polynomial is written to cout.

void test_np(const polynomial& test);

// Post conditon: The user has been prompted for the e value. The

// value of test.next_term(e) and test.previous_term(e) are written to cout.

int main()

{

    polynomial p[MANY];

    size_t current_index = 0;

    char command;

    size_t i;

    cout << "Polynomials ";

    for (i = 0; i < MANY; ++i)

        cout << char('A' + i) << ' ';

    cout << "have all been initialized." << endl;

    do

    {

        print_menu();

        command = toupper(get_command());

        switch(command)

        {

        case 'S': current_index = set_current( );

            break;

        case '1': test_assign(p[current_index]);

            break;

        case '2': test_add(p[current_index]);

            break;

        case 'C': test_clear(p[current_index]);

            break;

        case 'V':

            cout << char(current_index + 'A') << ": ";

            view(p[current_index]);

            break;

        case 'A': view_all(p);

            break;

        case 'E': test_eval(p[current_index]);

            break;

        case 'N': test_np(p[current_index]);

            break;

        case 'D':

            cout << char(current_index + 'A') << ".derivative: ";

            view(p[current_index].derivative( ));

            break;

        case '+':

            cout << "A + B: ";

            view(p[0] + p[1]);

            break;

        case '-':

            cout << "A - B: ";

            view(p[0] - p[1]);

            break;

        case '*':

            cout << "A * B: ";

            view(p[0] * p[1]);

            break;

        case 'Q': // Do nothing..

            break;

        default:   cout << "Invalid command." << endl;

            break;

        }

    }

    while(command != 'Q');

    return (EXIT_SUCCESS);

}

void print_menu()

{

    cout << "----------------- The Commands -----------------" << endl;

    cout << "S - set the current Polynomial to work on" << endl;

    cout << " -   -   -   -   -   -   -   -   -   -   -   -" << endl;

    cout << "1 - use the assign_coef function" << endl;

    cout << "2 - use the add_to_coef function" << endl;

    cout << "C - use the clear function" << endl;

    cout << "V - view the current polynomial by using <<" << endl;

    cout << "A - view all polynomials by using <<" << endl;

    cout << "E - evaluate current polynomial by using () op" << endl;

    cout << "N - use the next_term and previous_term functions" << endl;

//    cout << "G - use the gif function" << endl;

    cout << "D - view derivative of current polynomial" << endl;

    cout << "+ - view A + B" << endl;

    cout << "- - view A - B" << endl;

    cout << "* - view A * B" << endl;

    cout << " -   -   -   -   -   -   -   -   -   -   -   -" << endl;

    cout << "Q - quit this interactive test program" << endl;

    cout << "-------------------------------------------------" << endl;

}

char get_command()

{

    char command;

    cout << ">";

    cin >> command;

    return(toupper(command));

}

void view(const polynomial& test)

{

    cout << test

        << " (degree is " << test.degree( ) << ")" << endl;

}

size_t set_current( )

{

    size_t i;

    char command;

   

    do

    {

        cout << "Polynomials ";

        for (i = 0; i < MANY; ++i)

            cout << char('A' + i) << ' ';

        cout << "." << endl;

        cout << "Enter the polynomial you want to work on: ";

        command = toupper(get_command());

    }

    while ((command < 'A') || (command >= char('A' + MANY)));

    return command - 'A';

}

void test_add(polynomial& test)

{

    double coefficient;

    unsigned int exponent;

    cout << "Enter exponent: ";

    cin >> exponent;

    cout << "Enter coefficient: ";

    cin >> coefficient;

    test.add_to_coef(coefficient, exponent);

    cout << "After adding: ";

    view(test);

}

void test_assign(polynomial& test)

{

    double coefficient;

    unsigned int exponent;

    cout << "Enter exponent: ";

    cin >> exponent;

    cout << "Enter coefficient: ";

    cin >> coefficient;

    test.assign_coef(coefficient, exponent);

    cout << "After assigning: ";

    view(test);

}

void test_eval(const polynomial& test)

{

    double x_value;

    cout << "Enter the x value: ";

    cin >> x_value;

    cout << "For the poly: ";

    view(test);

    cout << "The evaluation returned is " << test(x_value) << endl;

}

void view_all(const polynomial p[])

{

    size_t i;

   

    cout << endl;

    for (i = 0; i < MANY; ++i)

    {

        cout << char(i + 'A') << ": ";

        view(p[i]);

    }

}

void test_clear(polynomial& test)

{

    test.clear( );

    cout << "After clearing: ";

    view(test);

}

void test_np(const polynomial& test)

{

    unsigned int exponent;

    cout << "Enter exponent: ";

    cin >> exponent;

    cout << "For polynomial: ";

    view(test);

    cout << "next_term(" << exponent << ") = "

        << test.next_term(exponent) << endl;

    cout << "previous_term(" << exponent << ") = "

        << test.previous_term(exponent) << endl;

}

Explanation / Answer

//main.cpp
#include <cctype> // Provides toupper
#include <iostream> // Provides cout and cin
#include <cstdlib> // Provides EXIT_SUCCESS
#include "poly.h" // Provides the polynomial class
using namespace std;
using namespace main_savitch_5;

const unsigned int MANY = 3; // Number of polynomials allowed in this test program.


// PROTOTYPES for functions used by this test program:
void print_menu();
// Postcondition: The menu has been written to cout.

size_t set_current( );
// Postcondition: Return value is index for a new current polynomial.

char get_command();
// Postcondition: The user has been prompted for a character.
// The entered charatcer will be returned, translated to upper case.

void view(const polynomial& test);
//Postcondition: The polynomial passed has been sent to cout.

void view_all(const polynomial a[]);
//Postcondition: All polynomials has been written to cout.

void test_add(polynomial& test);
// Postcondition: The user has been prompted for a coefficent and degree of
// the term added. The resulting polynomial has been written to cout.

void test_assign(polynomial& test);
// Postcondition: The user has been prompted for the degree and the coeffinient
// to be set. The resulting polynomial has been written to cout.

void test_clear(polynomial& test);
// Postcondition: test.clear( ) has been activated.
// to be set. The resulting polynomial has been written to cout.

//void test_gif(const polynomial& test);
// Postcondition: The user has been prompted for the range of the gif file.
// The gif file of the graph of the polynomial has been written to disk.

void test_eval(const polynomial& test);
// Post conditon: The user has been prompted for the x value. The evaluation
// of the polynomial is written to cout.

void test_np(const polynomial& test);
// Post conditon: The user has been prompted for the e value. The
// value of test.next_term(e) and test.previous_term(e) are written to cout.


int main()
{
polynomial p[MANY];
size_t current_index = 0;
char command;
size_t i;

cout << "Polynomials ";
for (i = 0; i < MANY; ++i)
   cout << char('A' + i) << ' ';
cout << "have all been initialized." << endl;

do
{
print_menu();
command = toupper(get_command());

switch(command)
{
   case 'S': current_index = set_current( );
   break;
   case '1': test_assign(p[current_index]);
   break;
   case '2': test_add(p[current_index]);
   break;
   case 'C': test_clear(p[current_index]);
   break;
   case 'V':
   cout << char(current_index + 'A') << ": ";
   view(p[current_index]);
   break;
   case 'A': view_all(p);
   break;
   case 'E': test_eval(p[current_index]);
   break;
   case 'N': test_np(p[current_index]);
   break;
//   case 'G': test_gif(p[current_index]);
//   break;
   case 'D':
   cout << char(current_index + 'A') << ".derivative: ";
   view(p[current_index].derivative( ));
   break;
   case '+':
   cout << "A + B: ";
   view(p[0] + p[1]);
   break;
   case '-':
   cout << "A - B: ";
   view(p[0] - p[1]);
   break;
   case '*':
   cout << "A * B: ";
   view(p[0] * p[1]);
   break;
   case 'Q': // Do nothing..
   break;
   default: cout << "Invalid command." << endl;
   break;
}
}
while(command != 'Q');

return (EXIT_SUCCESS);
}

void print_menu()
{
cout << "----------------- The Commands -----------------" << endl;
cout << "S - set the current Polynomial to work on" << endl;
cout << " - - - - - - - - - - - -" << endl;
cout << "1 - use the assign_coef function" << endl;
cout << "2 - use the add_to_coef function" << endl;
cout << "C - use the clear function" << endl;
cout << "V - view the current polynomial by using <<" << endl;
cout << "A - view all polynomials by using <<" << endl;
cout << "E - evaluate current polynomial by using () op" << endl;
cout << "N - use the next_term and previous_term functions" << endl;
cout << "G - use the gif function" << endl;
cout << "D - view derivative of current polynomial" << endl;
cout << "+ - view A + B" << endl;
cout << "- - view A - B" << endl;
cout << "* - view A * B" << endl;
cout << " - - - - - - - - - - - -" << endl;
cout << "Q - quit this interactive test program" << endl;
cout << "-------------------------------------------------" << endl;
}

char get_command()
{
char command;

cout << ">";
cin >> command;

return(toupper(command));
}

void view(const polynomial& test)
{
cout << test
   << " (degree is " << test.degree( ) << ")" << endl;
}

size_t set_current( )
{
size_t i;
char command;
  
do
{
   cout << "Polynomials ";
   for (i = 0; i < MANY; ++i)
   cout << char('A' + i) << ' ';
   cout << "." << endl;
   cout << "Enter the polynomial you want to work on: ";
   command = toupper(get_command());
}
while ((command < 'A') || (command >= char('A' + MANY)));
return command - 'A';
}

void test_add(polynomial& test)
{
double coefficient;
unsigned int exponent;

cout << "Enter exponent: ";
cin >> exponent;
cout << "Enter coefficient: ";
cin >> coefficient;

test.add_to_coef(coefficient, exponent);
cout << "After adding: ";
view(test);
}

void test_assign(polynomial& test)
{
double coefficient;
unsigned int exponent;

cout << "Enter exponent: ";
cin >> exponent;
cout << "Enter coefficient: ";
cin >> coefficient;

test.assign_coef(coefficient, exponent);
cout << "After assigning: ";
view(test);
}

void test_eval(const polynomial& test)
{
double x_value;
cout << "Enter the x value: ";
cin >> x_value;

cout << "For the poly: ";
view(test);
cout << "The evaluation returned is " << test(x_value) << endl;
}

void view_all(const polynomial p[])
{
size_t i;
  
cout << endl;

for (i = 0; i < MANY; ++i)
{
   cout << char(i + 'A') << ": ";
   view(p[i]);
}
}


void test_clear(polynomial& test)
{
test.clear( );
cout << "After clearing: ";
view(test);
}

void test_np(const polynomial& test)
{
unsigned int exponent;

cout << "Enter exponent: ";
cin >> exponent;

cout << "For polynomial: ";
view(test);
cout << "next_term(" << exponent << ") = "
   << test.next_term(exponent) << endl;
cout << "previous_term(" << exponent << ") = "
   << test.previous_term(exponent) << endl;
}

=========================================================================

//poly.cpp

#include "poly.h"
using namespace std;

namespace main_savitch_5
{
   //Constructor
   polynomial::polynomial(double c, unsigned int exponent)
   {
       EPSILON = std::numeric_limits<double>::epsilon();
       head_ptr = new polynode(c, 0);
       if (exponent == 0 || fabs(c) < EPSILON)
       {
           recent_ptr = head_ptr;
           tail_ptr = head_ptr;
           current_degree = 0;
       }
       else
       {
           head_ptr->set_coef(0);
           polynode* p = new polynode(c, exponent, nullptr, head_ptr);
           head_ptr->set_fore(p);
           tail_ptr = p;
           recent_ptr = p;
           current_degree = exponent;
       }
}
   //Assignment operator
polynomial& polynomial::operator=(const polynomial& source)
{
       EPSILON = std::numeric_limits<double>::epsilon();
       if (this == &source)
           return *this;
       if (head_ptr != nullptr)
       {  
           clear();
           delete head_ptr;
       }
       tail_ptr = nullptr;
       head_ptr = nullptr;
       recent_ptr = nullptr;
  
       if (source.head_ptr != nullptr)
       {
           head_ptr = new polynode(source.head_ptr->coef(), source.head_ptr->exponent());
           tail_ptr = head_ptr;
           recent_ptr = head_ptr;
           current_degree = 0;
  
           for (unsigned int expo = source.next_term(0); expo != 0; expo = source.next_term(expo))
               assign_coef(source.coefficient(expo), expo);
       }
       return *this;
}
  
   //copy constructor
polynomial::polynomial(const polynomial& source)
{
       EPSILON = std::numeric_limits<double>::epsilon();
       head_ptr = nullptr;
       *this = source;
}
//Deletes the polynodes and calls clear to remove each node
polynomial::~polynomial()
{
       clear();
       delete head_ptr;
       head_ptr = nullptr;
       tail_ptr = nullptr;
       recent_ptr = nullptr;
       current_degree = 0;
}

//Steps trhough each node in the list and removes it's values
void polynomial::clear()
{
       polynode* curr_node = head_ptr;
       while (head_ptr->fore() != nullptr)
       {
           curr_node = head_ptr->fore();
           delete head_ptr;
           head_ptr = curr_node;
       }
       head_ptr->set_coef(0);
       head_ptr->set_exponent(0);
       current_degree = 0;
       tail_ptr = head_ptr;
       recent_ptr = head_ptr;
}
  
//sets recent polynode
double polynomial::coefficient(unsigned int exponent) const
{
       set_recent(exponent);
       if (recent_ptr->exponent() == exponent)
           return recent_ptr->coef();
       return 0;
}

//add on to the coefficient of a specific polynode
void polynomial::add_to_coef(double amount, unsigned int exponent)
{
           set_recent(exponent);
       if (fabs(amount) < EPSILON)
           return;
       else
       {
           if (recent_ptr->exponent() < exponent)
           {
               polynode* new_node = new polynode(amount, exponent, recent_ptr->fore(), recent_ptr);
               if (recent_ptr->fore() != nullptr)
                   recent_ptr->fore()->set_back(new_node);
               else
                   tail_ptr = new_node;
               recent_ptr->set_fore(new_node);
               if (exponent > current_degree && fabs(amount) >= EPSILON)
                   current_degree = exponent;
           }
           else
           {
               if (exponent == 0)
                   recent_ptr->set_coef(recent_ptr->coef() + amount);
               else
               {
                   if (exponent == current_degree)
                   {  
                       if (fabs(amount + recent_ptr->coef()) < EPSILON)
                       {
                           tail_ptr = recent_ptr->back();
                           delete recent_ptr;
                           recent_ptr = tail_ptr;
                           tail_ptr->set_fore(nullptr);
                           current_degree = tail_ptr->exponent();
                       }
                       else
                           recent_ptr->set_coef(recent_ptr->coef() + amount);
                   }
                   else
                   {
                       if (fabs(amount + recent_ptr->coef()) < EPSILON)
                       {
                           recent_ptr->back()->set_fore(recent_ptr->fore());
                           recent_ptr->fore()->set_back(recent_ptr->back());
                           delete recent_ptr;
                           recent_ptr = recent_ptr->back();
                       }
                       else
                           recent_ptr->set_coef(recent_ptr->coef() + amount);
                   }
               }
           }
       }
   }

//change the coefficient of a specific polynode
void polynomial::assign_coef(double coefficient, unsigned int exponent)
{
       set_recent(exponent);
       if (fabs(coefficient) < EPSILON && exponent > current_degree)
           return;
       else
           if (recent_ptr->exponent() < exponent)
           {
               polynode* new_node = new polynode(coefficient, exponent, recent_ptr->fore(), recent_ptr);
               if (recent_ptr->fore() != nullptr)
               {
                   recent_ptr->fore()->set_back(new_node);
               }
               else
               {
                   tail_ptr = new_node;
               }
               recent_ptr->set_fore(new_node);
               if (exponent > current_degree)
                   current_degree = exponent;
               recent_ptr = new_node;
           }
           else
               if (fabs(coefficient) > EPSILON || exponent == 0)
               {
                   recent_ptr->set_coef(coefficient);
                   if (exponent > current_degree)
                       current_degree = exponent;
               }
               else
                   if (exponent == current_degree)
                   {
                       tail_ptr = recent_ptr->back();
                       delete recent_ptr;
                       recent_ptr = tail_ptr;
                       tail_ptr->set_fore(nullptr);
                       current_degree = tail_ptr->exponent();
                   }
                   else
                   {
                       recent_ptr->back()->set_fore(recent_ptr->fore());
                       recent_ptr->fore()->set_back(recent_ptr->back());
                       polynode* to_delete = recent_ptr;
                       recent_ptr = recent_ptr->back();
                       delete to_delete;
                   }
}
//Points recent to the next term in the list
unsigned int polynomial::next_term(unsigned int exponent) const
{
       if (exponent >= current_degree)
       {
           return 0;
       }
       set_recent(exponent);   
       if (recent_ptr->fore() == nullptr)
       {
           return 0;
       }
       return recent_ptr->fore()->exponent();
}

//points to the previous term in the list
   unsigned int polynomial::previous_term(unsigned int exponent) const
{
       if (exponent <= 0) return UINT_MAX;
       set_recent(exponent - 1);
       if (recent_ptr == nullptr) return UINT_MAX;
       if (recent_ptr->exponent() == 0 && fabs(recent_ptr->coef()) < EPSILON)
           return UINT_MAX;
       else
       {
           return recent_ptr->exponent();
       }
       return UINT_MAX;
}
  
//set what the recent_ptr is looking at
void polynomial::set_recent(unsigned int exponent) const
{
       if (exponent == 0)
       {
           recent_ptr = head_ptr;
       }
       else if (exponent >= current_degree)
           {
               recent_ptr = tail_ptr;
           }
           else
               if (exponent < recent_ptr->exponent())
               {
                   while (recent_ptr->back() != nullptr && recent_ptr->exponent() > exponent)
                   recent_ptr = recent_ptr->back();
               }
               else
               {  
                   while (recent_ptr->fore() != nullptr && recent_ptr->exponent() < exponent)
                       recent_ptr = recent_ptr->fore();
                   if (recent_ptr->exponent() > exponent)
                       recent_ptr = recent_ptr->back();
               }
   }
  
double polynomial::eval(double x) const
{
       double total = 0;
       unsigned int exp = next_term(0);
       while (exp != 0){
           //adds the power of x to exp multiplied by the coefficiet to the total
               total += pow(x, exp) * coefficient(exp);
               //move to the next node
               exp = next_term(exp);
       }
       return total;
}

polynomial polynomial::derivative() const
{
       polynomial p_prime;
       double coeff;
       unsigned int exp = 0;
       //set the coefficient to be the exponent multiplied by the coefficient
       coeff = exp * coefficient(exp);
       //assigns the coefficient to be to be coeff and the exponent 1 less
       p_prime.assign_coef(coeff, exp-1);
       //move to the next node
       exp = next_term(exp);
       //Do it for the rest
       while(exp !=0){
           coeff = exp * coefficient(exp);
           p_prime.assign_coef(coeff, exp-1);
           exp = next_term(exp);
       }
       return p_prime;
}
  
polynomial operator+(const polynomial& p1, const polynomial& p2)
{
       polynomial p = p1;
       unsigned int exp = 0;
       //adds the coefficent of p2 to p
       p.add_to_coef(p2.coefficient(exp), exp);
       //moves to next polnode
       exp = p2.next_term(exp);
       //runs it for the rest after 00
       while(exp!=0){
           p.add_to_coef(p2.coefficient(exp), exp);
           exp = p2.next_term(exp);
       }
      
       return p;
}
  
polynomial operator-(const polynomial& p1, const polynomial& p2)
{
       //Creates a new polynomial with the contents of p1
       polynomial p = p1;
       unsigned int exp = 0;
       //adds the negative of the coefficient to the first coefficent
       p.add_to_coef(-1*p2.coefficient(exp), exp);
       //moves to the next node
       exp = p2.next_term(exp);
      
       //do it for every node in the second polynomial
       while(exp != 0){
           p.add_to_coef(-1*p2.coefficient(exp), exp);
           exp = p2.next_term(exp);
       }
       return p;
}
  
polynomial operator*(const polynomial& p1, const polynomial& p2)
{      
       polynomial p;
       unsigned int exp1 = 0;
       unsigned int exp2 = 0;
       //get the 0*0 exponent
       p.add_to_coef(p1.coefficient(exp1) * p2.coefficient(exp2), exp1 + exp2);
       //gets the 0 * the exponents of polynode 2
       for(exp2 = p2.next_term(exp2); exp2 != 0; exp2 = p2.next_term(exp2)){
           p.add_to_coef(p1.coefficient(exp1) * p2.coefficient(exp2), exp1 + exp2);
       }
       //Does the rest of the multiply outs functions
       for(exp1 = p1.next_term(0); exp1 != 0; exp1 = p1.next_term(exp1)){
           exp2 = 0;
           p.add_to_coef(p1.coefficient(exp1) * p2.coefficient(exp2), exp1 + exp2);
           exp2 = p2.next_term(exp2);
           while(exp2 != 0){
               p.add_to_coef(p1.coefficient(exp1) * p2.coefficient(exp2), exp1 + exp2);
               exp2 = p2.next_term(exp2);
           }
       }
      
       return p;
}

ostream& operator << (ostream& out, const polynomial& p)
{
       unsigned int expo = 0;
       //Run through once
       //prints the coefficent and the exponent on the sides of a x
       out << p.coefficient(expo) << "*x^" << expo;
       //moves to next exponent
       expo = p.next_term(expo);
       //print next node
       if (expo != 0) out << " + ";
      
       //do the rest
       while(expo != 0){
           out << p.coefficient(expo) << "*x^" << expo;
           expo = p.next_term(expo);
           if (expo != 0) out << " + ";
       }
       return out;
}
  
void polynomial::find_root(
   double& answer,
   bool& success,
   unsigned int& iterations,
   double guess,
   unsigned int maximum_iterations,
   double epsilon) const
{
   }
}

============================================================================

poly.h

#ifndef POLY2_H
#define POLY2_H
#include <cstdlib> // Provides nullptr
#include <iostream> // Provides ostream
#include <cmath>   // provides pow()
#include <climits> // Provides UINT_MAX
#include <limits>   // provides machine epsilon

// If your compiler does not support namespaces, then please delete the
// following line and the set of brackets that follow.
namespace main_savitch_5
{
class polynode
{
       public:
       // CONSTRUCTOR: Creates a node containing a specified initial
       // coefficient (init_coef), initial exponent (init_exponent), and
       // initial links forward and backward (init_fore and init_back).
       polynode(
           double init_coef = 0.0,
           unsigned int init_exponent = 0,
           polynode* init_fore = nullptr,
           polynode* init_back = nullptr
   )
   {
           coef_field = init_coef;
           exponent_field = init_exponent;
           link_fore = init_fore;
           link_back = init_back;
   }

       // Member functions to set the fields:
   void set_coef(double new_coef)
   { coef_field = new_coef; }
   void set_exponent(unsigned int new_exponent)
   { exponent_field = new_exponent; }
   void set_fore(polynode* new_fore)
   { link_fore = new_fore; }
   void set_back(polynode* new_back)
   { link_back = new_back; }

       // Const member functions to retrieve current coefficient or exponent:
       double coef( ) const { return coef_field; }
       unsigned int exponent( ) const { return exponent_field; }

       // Two slightly different member functions to retrieve each link:
       const polynode* fore( ) const { return link_fore; }
       polynode* fore( ) { return link_fore; }
       const polynode* back( ) const { return link_back; }
   polynode* back( ) { return link_back; }
  
private:
       double coef_field;
       unsigned int exponent_field;
       polynode *link_fore;
       polynode *link_back;
};

class polynomial
{
       public:
           // CONSTRUCTORS and DESTRUCTOR
           polynomial(double c = 0.0, unsigned int exponent = 0);
           polynomial(const polynomial& source);
           ~polynomial( );

           // MODIFICATION MEMBER FUNCTIONS
           polynomial& operator =(const polynomial& source);
           void add_to_coef(double amount, unsigned int exponent);
           void assign_coef(double coefficient, unsigned int exponent);
           void clear( );
  
           // CONSTANT MEMBER FUNCTIONS
           double coefficient(unsigned int exponent) const;
           unsigned int degree( ) const { return current_degree; }
           polynomial derivative( ) const;
           double eval(double x) const;
           void find_root(
               double& answer,
               bool& success,
               unsigned int& iterations,
               double guess = 0,
               unsigned int maximum_iterations = 100,
               double epsilon = 1e-8
           ) const;
           unsigned int next_term(unsigned int e) const;
           unsigned int previous_term(unsigned int e) const;
  
           // CONSTANT OPERATORS
           double operator( ) (double x) const { return eval(x); }
  
       private:
           double EPSILON;
          
           polynode *head_ptr; // Head pointer for list of terms
           polynode *tail_ptr; // Tail pointer for list of terms
           mutable polynode *recent_ptr; // Most recently used term
           unsigned int current_degree; // Current degree of the polynomial
           // A private member function to aid the other functions:
           void set_recent(unsigned int exponent) const;
};
  
// NON-MEMBER BINARY OPERATORS
polynomial operator +(const polynomial& p1, const polynomial& p2);
polynomial operator -(const polynomial& p1, const polynomial& p2);
polynomial operator *(const polynomial& p1, const polynomial& p2);
  
// NON-MEMBER OUTPUT FUNCTIONS
std::ostream& operator << (std::ostream& out, const polynomial& p);
}

  

#endif

============================================================================

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote