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...
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...
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...
C++ program homework question 1 1. Create and implement a class called clockType with the following...
C++ program homework question 1 1. Create and implement a class called clockType with the following data and methods (60 Points.): Data: Hours, minutes, seconds Methods: Set and get hours Set and get minutes Set and get seconds printTime(…) to display time in the form of hh:mm:ss default and overloading constructor Overloading Operators: << (extraction) operator to display time in the form of hh:mm:ss >> (insertion) operator to get input for hours, minutes, and seconds operator+=(int x) (increment operator) to...
1. You are given Stack.java, an interface class for Stacks. /* Use an array to implement...
1. You are given Stack.java, an interface class for Stacks. /* Use an array to implement the Stack.java in a class called ArrayStack.java that uses Generics. Write a main function that creates two stacks, one containing 10 Integers and a different one containing 10 Strings, and reverses there contents using a method called reverse that takes as a paramater a Generic array. You will need to implement all the methods of Stack.java as well as create a toString method in...
1. Circle: Implement a Java class with the name Circle. It should be in the package...
1. Circle: Implement a Java class with the name Circle. It should be in the package edu.gcccd.csis. The class has two private instance variables: radius (of the type double) and color (of the type String). The class also has a private static variable: numOfCircles (of the type long) which at all times will keep track of the number of Circle objects that were instantiated. Construction: A constructor that constructs a circle with the given color and sets the radius to...
Java the goal is to create a list class that uses an array to implement the...
Java the goal is to create a list class that uses an array to implement the interface below. I'm having trouble figuring out the remove(T element) and set(int index, T element). I haven't added any custom methods other than a simple expand method that doubles the size by 2. I would prefer it if you did not use any other custom methods. Please use Java Generics, Thank you. import java.util.*; /** * Interface for an Iterable, Indexed, Unsorted List ADT....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT