Question

In: Computer Science

           Homework: Polynomial Using Array Description: Implement a polynomial class (1) Name your class...

           Homework: Polynomial Using Array

Description: Implement a polynomial class

(1) Name your class Polynomial

(2) Use array of doubles to store the coefficients so that the coefficient for x^k is stored in the location [k] of the array.

(3) define the following methods:

a. public Polynomial()

   POSTCONDITION: Creates a polynomial represents 0

b. public Polynomial(double a0)

   POSTCONDITION: Creates a polynomial has a single x^0 term with coefficient a0

c. public Polynomial(Polynomial p)

   POSTCONDITION: Creates a polynomial that is the copy of p

d. public void add_to_coef(double amount, int exponent)

POSTCONDITION: Adds the given amount to the coefficient of the specified exponent.
Note: the exponent is allowed to be greater than the degree of the polynomial   
example: if p = x + 1, after p.add_to_coef(1, 2), p = x^2 + x + 1
  

e. public void assign_coef(double coefficient, int exponent)
POSTCONDITION: Sets the coefficient for the specified exponent.
Note: the exponent is allowed to be greater than the degree of the polynomial   

f. public double coefficient(int exponent)
POSTCONDITION: Returns coefficient at specified exponent of this polynomial.
Note: the exponent is allowed to be greater than the degree of the polynomial   
e.g. if p = x + 1; p.coeffcient(3) should return 0

g. public double eval(double x)
POSTCONDITION: The return value is the value of this polynomial with the given value for the variable x.
Do not use power method from Math, which is very low efficient

h. public string toString()

   POSTCONDITION: return the polynomial as a string like “2x^2 + 3x + 4”
   
Important only non-zero terms unless the polynomial is 0

i. public Polynomial add(Polynomial p)
POSTCONDITION:
this object and p are not changed   
return a polynomial that is the sum of p and this polynomial


j. public Polynomial multiply(Polynomial p)
POSTCONDITION:
this object and p should not be changed
returns a new polynomial obtained by multiplying this term and p. For example, if this polynomial is
2x^2 + 3x + 4 and p is 5x^2 - 1x + 7, then at the end of this function, it will return the polynomial 10x^4 + 13x^3 + 31x^2 + 17x + 28.

k. Write a single main method to test ALL the methods and classes.
You can hard code the polynomials, just like we did for the first homework.

Solutions

Expert Solution

Here is the code with the implementation as mentioned in the problem,

Polynomial.java

public class Polynomial {
    private double[] coef;  // coefficients
    private int deg;     // degree of polynomial (0 for the zero polynomial)

    public Polynomial(){
        coef = new double[1];
        deg = 0;
    }

    public Polynomial(double a0){
        coef = new double[]{a0};
        deg = degree();
    }

    public Polynomial(Polynomial p){
        coef = p.coef;
        deg = p.deg;
    }

    private void updateCoefficient(int power){
        coef = new double[power+1];
        deg = degree();
    }

    public void add_to_coef(double amount, int exponent){
        if(exponent < coef.length){
            coef[exponent] += amount;
        }
        else{
            double[] updatedCoef = new double[exponent+1];
            for(int i=0; i<coef.length; i++) updatedCoef[i] = coef[i];
            updatedCoef[exponent] = amount;
            coef = updatedCoef;
        }
        deg = degree();
    }

    public int degree() {
        int d = 0;
        for (int i = 0; i < coef.length; i++)
            if (coef[i] != 0) d = i;
        return d;
    }

    public void assign_coef(double coefficient, int exponent){
        if(exponent < coef.length){
            coef[exponent] = coefficient;
        }
        else{
            double[] updatedCoef = new double[exponent+1];
            for(int i=0; i<coef.length; i++) updatedCoef[i] = coef[i];
            updatedCoef[exponent] = coefficient;
            coef = updatedCoef;
        }
        deg = degree();
    }

    public double coefficient(int exponent){
        if(exponent < coef.length) return coef[exponent];
        return 0.0;
    }

    public double evaluate(double x) {
        double p = 0;
        for (int i = deg; i >= 0; i--)
            p = coef[i] + (x * p);
        return p;
    }

    public Polynomial add(Polynomial p){
        Polynomial a = this;
        Polynomial c;
        if(a.deg <= p.deg){
            c = new Polynomial(p);
            for (int i = 0; i <= a.deg; i++) c.coef[i] += a.coef[i];
        }
        else{
            c = new Polynomial(a);
            for (int i = 0; i <= p.deg; i++) c.coef[i] += p.coef[i];
        }
        c.deg = c.degree();
        return c;
    }

    public Polynomial multiply(Polynomial p){
        Polynomial a = this;
        Polynomial c = new Polynomial();
        c.updateCoefficient(this.deg + p.deg);
        for (int i = 0; i <= a.deg; i++)
            for (int j = 0; j <= p.deg; j++)
                c.coef[i+j] += (a.coef[i] * p.coef[j]);
        c.deg = c.degree();
        return c;
    }

    public String toString() {
        if (deg ==  0) return "" + coef[0];
        if (deg ==  1) return coef[1] + "x + " + coef[0];
        StringBuilder s = new StringBuilder(coef[deg] + "x^" + deg);
        for (int i = deg-1; i >= 0; i--) {
            if      (coef[i] == 0) continue;
            else if (coef[i]  > 0) s.append(" + ").append(coef[i]);
            else if (coef[i]  < 0) s.append(" - ").append(-coef[i]);
            if      (i == 1) s.append("x");
            else if (i >  1) s.append("x^").append(i);
        }
        return s.toString();
    }


    public static void main(String[] args) {
        Polynomial zero = new Polynomial();

        Polynomial p1   = new Polynomial(4);
        p1.assign_coef(2, 1);
        p1.assign_coef(5, 2);
        p1.add_to_coef(1,1);
        Polynomial p2   = new Polynomial(3);
        p2.assign_coef(2, 1);
        p2.assign_coef(5, 2);
        p2.add_to_coef(1,1);
        Polynomial mulPoly    = p1.multiply(p2);
        Polynomial addPoly    = p1.add(p2);

        System.out.println("Zero(x) =     " + zero);
        System.out.println("p1(x) =     " + p1);
        System.out.println("p2(x) =     " + p2);
        System.out.println("mulPoly(x) =        " + mulPoly);
        System.out.println("addPoly(x) =        " + addPoly);

        System.out.println("Polynomial 1 degree : "+ p1.degree());
        System.out.println("Polynomial 2 evaluated with x = 2 equals to : "+ p2.evaluate(2.0));
        System.out.println("Polynomial 1 coefficient with exponent 1 : " + p1.coefficient(1));

    }
}

OUTPUT :

If you have any doubts feel free to ask in the comments. Also please don't forget to upvote the solution.


Related Solutions

Implement a class Polynomial that uses a dynamic array of doubles to store the coefficients for...
Implement a class Polynomial that uses a dynamic array of doubles to store the coefficients for a polynomial. Much of this work can be modelled on the C++ dynamic array of ints List that we discussed in class. This class does not need the method the overloaded += operator. Your class should have the following methods: Write one constructor that takes an integer n for the degree of a term and a double coefficient c for the coefficient of the...
Implement a Binary tree using an array using class.
Implement a Binary tree using an array using class.
In this homework you will implement a Library class that uses your Book and Person class...
In this homework you will implement a Library class that uses your Book and Person class from homework 2, with slight modifications. The Library class will keep track of people with membership and the books that they have checked out. Book.java You will need to modify your Book.java from homework 2 in the following ways: field: dueDate (private)             A String containing the date book is due.  Dates are given in the format "DD MM YYYY", such as "01 02 2017"...
Develop a class Polynomial. The internal representation of a Polynomial is an array of terms. Each...
Develop a class Polynomial. The internal representation of a Polynomial is an array of terms. Each term contains a coefficient and an exponent. has the coefficient 2 and the exponent 4. The User should be able to add as many terms as he wants, so the array should be dynamic. Develop a complete class containing proper constructor and destructor functions as well as set and get functions. The class should also provide the following overloaded operator capabilities: 1. Overload the...
Define and implement class Course. This class should contain the following fields: course name, course description,...
Define and implement class Course. This class should contain the following fields: course name, course description, department, time the course starts, weekday the course is held on (for simplicity, let us assume the course only meets once a week). This class should contain getters and setters for all its attributes. This class also needs at least one constructor. Save this class and its definition into a file named Course.java. Define and implement class Student. This class should contain the following...
Write a C++ class that implement two stacks using a single C++ array. That is, it...
Write a C++ class that implement two stacks using a single C++ array. That is, it should have functions pop_first(), pop_second(), push_first(…), push_second(…), size_first(), size_second(), …. When out of space, double the size of the array (similarly to what vector is doing). Notes: Complete all the functions in exercise_2.cpp, then submit this cpp file. pop_first() and pop_second() should throw std::out_of_range exception when stack is empty. CODE: #include <cstdio> #include <stdexcept> template <class T> class TwoStacks { public:   // Constructor, initialize...
Write a class to implement HeadTailListInterface. Instead of using an array, use a List object as...
Write a class to implement HeadTailListInterface. Instead of using an array, use a List object as your instance data variable. (List (Links to an external site.) from the Java standard library- not ListInterface!). Instantiate the List object to type ArrayList. Inside the methods of this class, invoke methods on the List object to accomplish the task. Note: some methods might look very simple... this does not mean they are wrong! There is one difference in how this class will work...
You will implement and test the sequence class using an array to store the sequence's items...
You will implement and test the sequence class using an array to store the sequence's items in C++. sequence1.h: The header file for the sequence class. Actually, you don't have to write much of this file. Start with the sequence1.h header file provided and add your name and other information at the top. Also, decide on appropriate private member variables, and declare these in the sequence class definition at the bottom of the header file. If some of your member...
Implement a stack in C++ using an array, not an array list. Make your stack size...
Implement a stack in C++ using an array, not an array list. Make your stack size 5 when you test it, but do not hardcode this! You should be able to change the size for testing purposes with the change of one variable. DO NOT use Stack class defined in C++ Implement the following methods in your stack class. stack() creates an empty stacks, stack s is new and empty. push(item) adds a new item to the stack s, stacks...
Homework Assignment 4 Instructions: Class name must be: HW4_yourName For example: Michael will name the class...
Homework Assignment 4 Instructions: Class name must be: HW4_yourName For example: Michael will name the class of homework assignment 4 as HW4_Michael Grading Rubric: Code running and as per the required conditions and giving expected output = 10 points File named as per instructions = 1 point Comments in code = 4 points Problem: Average calculation for a list Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT