Bill Teter
Office:          149 Redcay
Telephone:    2782
Office Hours:  Tuesday, Thursday 9:00-12:00

email:  william.teter@plattsburgh.edu

       

 

Lab 8    Polynomial class using an ArrayList

Create a class called Polynomial.  It will have an ArrayList<Double> instance variable called coeff that holds the coefficients for a polynomial.  You may want to have the degree as an instance variable as well, or you can use coeff.size()-1 as the polynomial's degree.  (It can be done either way).

When you do this lab you must write a test program to test each method as you add it to the Polynomial class.  The test code could be placed in a main method in the Polynomial class or in a separate Test.java program.  I will use my own test program to test your code.  So make sure your method headers are exactly as I have them below.  I suggest that your test program test one method at a time and then comment out this code as you prepare to test for the next method.  I would like to see what tests you have done.  The zero polynomial should be used often in your tests.

The constructor should allow an array of double as a parameter.  (I misspoke in class.  The addAll() method can not be used to copy coefficients from the array of double to the ArrayList().  Instead use a for loop and the add() method.)
    public Polynomial(double[] a)

Override the toString() method that returns a String rendition of the polynomial:  Leave out terms with zero coefficients.  The returned string should look like:

        2 + 3x + 4x^2 + 5x^3

Override the equals() method.  Two polynomials are equal when they have the same degree and matching coefficients are identical.  Remember to compare two Doubles with .equals, or caste them to doubles and use ==.

Provide a method to return the degree of a polynomial.  The degree is the highest exponent to appear with a non-zero coefficient.  Except that the polynomial with only a zero constant term has degree zero.  (Make sure you test this case!)  The header should be:
    public int degree()

Write a method with the header:
    public double eval(double d)
that returns the value of this polynomial obtained by substituting the parameter value d for the variable x.  The complexity of this should be lower than order n squared.  See problem 13b on page 282 of our text.

Write a class method (static) that computes the polynomial sum of two polynomials.  The header should be:
    public static Polynomial add(Polynomial p, Polynomial q)

Write a class method (static) that computes the polynomial product of two polynomials.  The header should be:
    public static Polynomial product(Polynomial p, Polynomial q)

Include in your documentation for each of the methods its worst case time complexity as a function of n, the degree of the polynomial.  For the product() and add() methods n will be the larger of the degrees of parameters p and q.