Hey im doing a composite method for polynomials in java and im having some problems. This is my code so far and im just lost...
public class Polynomial
{
final static private int mantissa = 52;
final static private double epsilon = Math.pow(2.0, -mantissa);
private double coefficient = 0.0;
private int power = 0;
private Polynomial successor = null;
public Polynomial(double coefficient, int power)
{
if (Double.isNaN(coefficient))return;
if (Math.abs(coefficient) < epsilon)return;
if (power < 0)return;
this.coefficient = coefficient;
this.power = power;
}
/* conditions
this(X) => sum(coefficient(i)*X^i:for(i=degree;i>=0;i--)) && X^0=1
this.degree()==this.power==highestPower
this.highestPoweredCoefficient==this.coefficient
this.successor!=null links to terms whose powers uniquely decrease
Polynomial(0.0,0)=(coefficient=0.0,power=0,successor=null)==0.0
if (coefficient==NaN) coefficient=0.0
if (abs(coefficient)<epsilon)) coefficient=0.0
if (power<0) power=0
if (this.degree()==0) abs(coefficient(0))>=0.0
if (this.degree()>0) abs(coefficient(i))>=epsilon for all i>=0
*/
private static void add(Polynomial polynomial, double coefficient, int power)
{
// This part is given to us
if (polynomial == null) return;
if (Math.abs(coefficient) < epsilon) coefficient = 0.0;
if (coefficient == 0.0) return;
if (power < 0) return;
// End of given code.
if (polynomial.coefficient == 0.0)
{
polynomial.coefficient = coefficient;
polynomial.power = power;
return;
}
if (polynomial.power == power)
{
polynomial.coefficient += coefficient;
if (Math.abs(polynomial.coefficient) < epsilon)
polynomial.coefficient = 0.0;
if (polynomial.coefficient != 0.0 || polynomial.power == 0) return;
if (polynomial.successor == null)
{
polynomial.power = 0;
return;
}
polynomial.coefficient = polynomial.successor.coefficient;
polynomial.power = polynomial.successor.power;
polynomial.successor = polynomial.successor.successor;
return;
}
// sets up variables used.
Polynomial old = null;
Polynomial checker = polynomial;
// goes through polynomial looking for the right place.
while (checker != null)
{
if (checker.power <= power)
{
break; //breaks the loop
}
old = checker;
checker = checker.successor;
}
//
if (old == null)
{
Polynomial node = new Polynomial(0.0,0); //creates a new node for insertion
node.coefficient = polynomial.coefficient;
node.power = polynomial.power;
node.successor = polynomial.successor;
polynomial.coefficient = coefficient;
polynomial.power = power;
polynomial.successor = node;
return;
}
//
if (checker == null || checker.power < power)
{
Polynomial node = new Polynomial(0.0,0); //sets a node for insertion
node.coefficient = coefficient;
node.power = power;
node.successor = checker;
old.successor = node;
return;
}
coefficient += checker.coefficient;
if (Math.abs(coefficient) < epsilon) coefficient = 0.0;
if (coefficient == 0.0)
old.successor = checker.successor;
else
checker.coefficient = coefficient;
}
final public int cardinality() {
int count = 1;
Polynomial traverser = this.successor;
while (traverser != null)
{ //THIS METHOD IS GIVEN TO US!
count++;
traverser = traverser.successor;
}
return count;
}
final public Polynomial clone() {
Polynomial result = new Polynomial(0.0, 0);
result.coefficient = this.coefficient;
result.power = this.power;
Polynomial traverserThis = this;
Polynomial traverserResult = result; //THIS METHOD IS GIVEN TO US!
while (traverserThis.successor != null) {
traverserResult.successor = new Polynomial(0.0, 0);
traverserThis = traverserThis.successor;
traverserResult = traverserResult.successor;
traverserResult.coefficient = traverserThis.coefficient;
traverserResult.power = traverserThis.power;
}
return result;
}
final public double coefficient(int power) {
if (power < 0) {
return 0.0;
}
Polynomial traverser = this;
do {
if (traverser.power < power) {
return 0.0;
}
if (traverser.power == power) { //THIS METHOD IS GIVEN TO US
return traverser.coefficient;
}
traverser = traverser.successor;
} while (traverser != null);
return 0.0;
}
//Method done by Callum
final public Polynomial composite(Polynomial that)
{
if (that == null)
{
return null;
}
Polynomial result = new Polynomial(0.0, 0); //the result polynomial
Polynomial current = this.clone(); //current is a copy of 'this' used for moving through
// the loop.
Polynomial tempHolder2 = that;
Polynomial tempHolder = new Polynomial(0.0, 0); //just a temporary holding polynomial
Polynomial thatNew = that.clone(); //another clone used for iteration.
while(current != null)
{
for( int i = 1; i <= current.power; i++)
{
tempHolder2 = tempHolder2.times(thatNew);
}
tempHolder.coefficient = current.coefficient;
tempHolder = tempHolder.times(tempHolder2);
current = current.successor; //Moves to next one
result = result.plus(tempHolder); //adds the values?
tempHolder = new Polynomial(0.0,0); //resets it for next use
}
return result;
}
final public int degree()
{
return this.power; //THIS METHOD WAS GIVEN TO US!
}
//METHOD DONE BY Mitchell Bowie
final public Polynomial differentiate()
{
Polynomial result = new Polynomial (0.0,0); //The result polynomial
Polynomial polynomial = this; //THIS polynomial. current one being assessed.
if (polynomial.power==0)
{
result.coefficient = (0.0); //returns 0.0 if its power = 0
return result;
}
Polynomial temp = new Polynomial (0.0,0); // just a polynomial used to add things up
while (polynomial != null) //goes through the polynomial
{
temp.coefficient = (polynomial.power*(polynomial.coefficient));
temp.power = (polynomial.power -1);
add (result, temp.coefficient, temp.power); //adds the new values to a polynomial
polynomial = polynomial.successor; //increments the polynomial //named result
}
return result; //returns the value added in the while loop
}
final public Polynomial[] dividedBy(Polynomial that)
{
//THIS METHOD WAS TOO HARD!!!!!
Polynomial[] polynomials={that};
return polynomials;
}
final public boolean equals(Polynomial that)
{
if (that == null) {
return false;
}
if (this.coefficient != that.coefficient) {
return false;
}
if (this.power != that.power) {
return false;
}
if (this.successor == null && that.successor == null) { //THIS METHOD WAS GIVEN TO US!
return true;
}
if (this.successor == null && that.successor != null) {
return false;
}
if (this.successor != null && that.successor == null) {
return false;
}
return this.successor.equals(that.successor);
}
//Method done by Mitchell
final public double evaluate(double variable)
{
if (Double.isNaN(variable)) { //THIS IS ALL GIVEN
variable = 0.0;
}
if (Math.abs(variable) < epsilon) {
variable = 0.0;
}
double value = 0.0;
//END OF GIVEN STUFF
Polynomial current = this.clone(); //creates a copy of this
while(current !=null) //goes through the copy until null
{
if(current.power > 0) //checks if power > 0
{
value += current.coefficient * Math.pow(variable, current.power);
}
else //if its not then it will do this!
{
value += current.coefficient; //adds the coefficient
}
current = current.successor; //iterates the loop
}
return value;// returns the value
}
//Method done by Mitchell and Callum
final public Polynomial integrate()
{
if (this.coefficient == 0.0)
{
return new Polynomial(0.0, 0); //Given part
}
Polynomial result = this.clone(); //why it was called result i dont know but this threw me
//for a long time. -.-
// End of given stuff
Polynomial result2 = new Polynomial(0.0, 0);
Polynomial tempHolder = new Polynomial(0.0, 0); //just holds temp values
while(result!=null)
{
tempHolder.coefficient = result.coefficient / (result.power +1);
tempHolder.power = result.power + 1; //adds 1 to the power of result and sets it to
//tempHolder
result2 = result2.plus(tempHolder);
result = result.successor; //iterates the loop
}
return result2; //returns result2 NOT result -.-
}
final public Polynomial minus(Polynomial that)
{
if (that == null) {
return null;
}
if (this.equals(that)) {
return new Polynomial(0.0, 0);
}
Polynomial result = this.clone(); //THIS METHOD WAS GIVEN
if (that.coefficient == 0.0) {
return result;
}
Polynomial traverser = that;
do {
add(result, -traverser.coefficient, traverser.power);
traverser = traverser.successor;
} while (traverser != null);
return result;
}
final public Polynomial plus(Polynomial that)
{
if (that == null) {
return null;
}
if (this.coefficient == 0.0) {
return that.clone();
}
Polynomial result = this.clone(); //THIS METHOD WAS GIVEN TO US!
if (that.coefficient == 0.0) {
return result;
}
Polynomial traverser = that;
do {
add(result, traverser.coefficient, traverser.power);
traverser = traverser.successor;
} while (traverser != null);
return result;
}
final public int powerMax()
{
int max = Integer.MIN_VALUE;
Polynomial traverser = this;
do {
if (max < traverser.power) { //THIS METHOD WAS GIVEN TO US!
max = traverser.power;
}
traverser = traverser.successor;
} while (traverser != null);
return max;
}
final public int powerMin()
{
int min = Integer.MAX_VALUE;
Polynomial traverser = this;
do {
if (min > traverser.power) { //THIS METHOD WAS GIVEN TO US!
min = traverser.power;
}
traverser = traverser.successor;
} while (traverser != null);
return min;
}
//TIMES METHOD BY Callum
//Take current polynomial and times it by that polynomial.
//Uses dual while loops to get the results needed.
final public Polynomial times(Polynomial that)
{
Polynomial result = new Polynomial (0.0,0);
Polynomial thiss = this;
int count = 0;
if (that == null)return null;
Polynomial newThat = that.clone(); //creates a clone of that
int length = that.cardinality();
if (thiss.coefficient == 0.0)
{
return result; //if this coefficient is 0.0 return 0.0
}
if (that.coefficient == 0.0)
{
return result; //if that coefficient is 0.0 return 0.0
}
while (thiss != null) //goes through thiss until its null
{
double thissc = thiss.coefficient; //sets the double to the coefficient
int thissp = thiss.power; //sets the int to the power
while (that !=null) //goes through that until null
{
double thatc = that.coefficient; //sets the double to that coefficient
int thatp = that.power; //sets the int to that power
double resultc = thissc*thatc; // sets the result double to this coeff times that coeff
int resultp = thissp+thatp; // sets the result int to this power plus that power
if (count == 0) //if its the first value in the result it will just override the values
{
result.coefficient = resultc; //sets the coeff
result.power = resultp; //sets the power
}
else
{
add(result,resultc, resultp); //adds the values to the result polynomial with add method
}
count++; //count increase so it doesnt over ride the values
that = that.successor; //iterates the inner loop!
}
that = newThat; //resets that to the start for next loop iteration!
thiss = thiss.successor; //iterates the loop!
}
return result; //returns what is in result!
}
final public String toString()
{
String string = "" + this.coefficient + (this.power == 0 ? "" : "*X^" + this.power);
Polynomial traverser = this.successor;
while (traverser != null) {
string += (traverser.coefficient > 0.0 ? "+" : "") //THIS METHOD WAS GIVENT TO US!
+ traverser.coefficient
+ (traverser.power == 0 ? "" : "*X^"
+ traverser.power);
traverser = traverser.successor;
}
return string;
}
}
I'd start with a Monomial:
package poly;
public class Monomial
{
private final double coeff;
private final int expon;
public Monomial()
{
this(0.0, 0);
}
public Monomial(double coeff)
{
this(coeff, 0);
}
public Monomial(double coeff, int expon)
{
this.coeff = coeff;
this.expon = expon;
}
public double getCoeff()
{
return coeff;
}
public int getExpon()
{
return expon;
}
public Monomial add(Monomial other)
{
if (this.expon != other.expon)
throw new IllegalArgumentException("Exponents must match in order to add");
return new Monomial((this.coeff+other.coeff), this.expon);
}
public Monomial sub(Monomial other)
{
if (this.expon != other.expon)
throw new IllegalArgumentException("Exponents must match in order to subtract");
return new Monomial((this.coeff-other.coeff), this.expon);
}
public Monomial mul(Monomial other)
{
return new Monomial((this.coeff*other.coeff), (this.expon+other.expon));
}
public Monomial div(Monomial other)
{
return new Monomial((this.coeff/other.coeff), (this.expon-other.expon));
}
#Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Monomial monomial = (Monomial) o;
if (Double.compare(monomial.coeff, coeff) != 0)
{
return false;
}
if (expon != monomial.expon)
{
return false;
}
return true;
}
#Override
public int hashCode()
{
int result;
long temp;
temp = coeff != +0.0d ? Double.doubleToLongBits(coeff) : 0L;
result = (int) (temp ^ (temp >>> 32));
result = 31 * result + expon;
return result;
}
#Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
if (coeff != 1.0) sb.append(coeff);
if (expon != 0) {
sb.append('x');
if (expon != 1) sb.append('^').append(expon);
}
return sb.toString();
}
}
And a unit test, of course:
package poly;
import org.junit.Assert;
import org.junit.Test;
public class MonomialTest
{
private static final double DELTA = 0.001;
#Test
public void testConstructor_Default()
{
Monomial test = new Monomial();
Assert.assertEquals("0.0", test.toString());
}
#Test
public void testConstructor_Constant()
{
Monomial test = new Monomial(2);
Assert.assertEquals("2.0", test.toString());
}
#Test
public void testConstructor()
{
Monomial test = new Monomial(6, 3);
Assert.assertEquals("6.0x^3", test.toString());
Assert.assertEquals(6.0, test.getCoeff(), DELTA);
Assert.assertEquals(3, test.getExpon());
}
#Test
public void testAddSuccess()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(3, 3);
Monomial expected = new Monomial(5, 3);
Assert.assertEquals(expected, x.add(y));
}
#Test(expected = IllegalArgumentException.class)
public void testAdd_MismatchedExponents()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(3, 4);
x.add(y);
}
#Test
public void testSubSuccess()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(3, 3);
Monomial expected = new Monomial(-1, 3);
Assert.assertEquals(expected, x.sub(y));
}
#Test(expected = IllegalArgumentException.class)
public void testSub_MismatchedExponents()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(3, 4);
x.sub(y);
}
#Test
public void testMulSuccess()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(3, 3);
Monomial expected = new Monomial(6, 6);
Assert.assertEquals(expected, x.mul(y));
}
#Test
public void testDivSuccess()
{
Monomial x = new Monomial(4, 4);
Monomial y = new Monomial(2, 3);
Monomial expected = new Monomial(2, 1);
Assert.assertEquals(expected, x.div(y));
}
#Test
public void testEquals_null()
{
Monomial x = new Monomial();
Assert.assertFalse(x.equals(null));
}
#Test
public void testEquals_reflexive()
{
Monomial x = new Monomial(2, 3);
Assert.assertTrue(x.equals(x));
}
#Test
public void testEquals_symmetric()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(2, 3);
Assert.assertTrue(x.equals(y) && y.equals(x));
Assert.assertEquals(x.hashCode(), y.hashCode());
}
#Test
public void testEquals_transitive()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(2, 3);
Monomial z = new Monomial(2, 3);
Assert.assertTrue(x.equals(y) && y.equals(z) && z.equals(x));
Assert.assertEquals(x.hashCode(), y.hashCode());
Assert.assertEquals(y.hashCode(), z.hashCode());
Assert.assertEquals(z.hashCode(), x.hashCode());
}
#Test
public void testEquals_differentCoefficients()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(3, 3);
Assert.assertFalse(x.equals(y));
Assert.assertFalse(x.hashCode() == y.hashCode());
}
#Test
public void testEquals_differentExponents()
{
Monomial x = new Monomial(2, 3);
Monomial y = new Monomial(2, 4);
Assert.assertFalse(x.equals(y));
Assert.assertFalse(x.hashCode() == y.hashCode());
}
}
Then I'd write a Polynomial that had a List<Monomial> as a private data member.
Perhaps you want a common interface for the two, since you said Composite. But this is a start.
Related
Could someone check my code for why I'm getting NullPointerExceptions in various methods? I've been racking my brain and can't figure out what is wrong.
I'm attempting to create a polynomial class that stores polynomials in a linked list using an inner class Terms. If you have any questions on the methods, please let me know!
public class Polynomial {
// Create the "Term" Inner Class for Handling the Respective Nodes for this Class
protected class Term {
int coefficient; // Coefficient of the Current Term
int exponent; // Exponent of the Current Term
Term next; // Reference to the Next Term in the Linked List (if Possible)
public Term (int coefficient, int exponent, Term next) { // General Constructor Method
this.coefficient = coefficient;
this.exponent = exponent;
this.next = next;
}
public Term (int coefficient, int exponent) { // No "Term next" (The Next Term Needs to be Null!)
this (coefficient, exponent, null);
}
public Term () { // Basic Constructor Method (No Input Necessary)
this (0, 0, null);
}
}
protected Term poly; // Starting Point (Dummy Header Node)
public Polynomial() { // General Constructor Method
poly = new Term();
clear();
}
public Polynomial(int [] terms) { // Constructor Method (Using an Integer Array of Coefficients and Exponents)
if (!(terms.length % 2 == 0)) { // This Array MUST Possess an Even, Positive Number of Elements (Alternating Coefficients and Corresponding Exponents)
throw new IllegalArgumentException("Your array must have an even, positive number of elements for use in our program. Thanks!");
}
else { // Proceed Normally...
poly = new Term(); // Dummy Header Node
clear();
setTerms(terms);
}
}
// Create the clear() Method for Promptly Resetting the Polynomial Back to 0
public void clear() {
poly.next = null;
}
// Create the setTerms(int [] terms) Method for Setting the Polynomial to the Appropriate Set of Terms
public void setTerms(int [] terms) {
Term temp = poly;
for (int i = 0; i < terms.length; i = i + 2) { // Incrementing By 2 (Each Polynomial Necessitates a Coefficient & Exponent, or Lack Thereof)
if (terms[i + 1] < 0) { // Polynomials CANNOT Have Coefficients with Negative Exponents
throw new IllegalArgumentException("Coefficients in polynomials must have positive exponents for use in our program. Thanks!");
}
temp.next = new Term(terms[i], terms[i + 1]);
temp = temp.next;
}
}
// Create the toString() for Outputting the Polynomial to the User's Screen
public String toString() {
String polynomialString = "";
boolean firstTerm = true;
if (poly.next == null) {
return "0"; // The ONLY Time 0 is Outputted as a Coefficient is if the Polynomial = 0
}
while (poly.next != null) { // Reached the Conclusion of the Linked List?
if (poly.next.coefficient > 0) { // Checking for Positivity
if (!firstTerm) { // First Term DOESN'T Need a "+" Sign
polynomialString = polynomialString + "+";
}
}
if (poly.next.coefficient == 1) {
if (poly.next.exponent == 1) {
polynomialString = polynomialString + "x"; // Print ONLY the Variable (x)
}
else {
polynomialString = polynomialString + "x^" + poly.next.exponent; // Otherwise, Print "x^exponent"
}
}
else if (poly.next.coefficient == -1) {
if (poly.next.exponent == 1) {
polynomialString = polynomialString + "-x"; // Print ONLY the Variable (x)
}
else {
polynomialString = polynomialString + "-x^" + poly.next.exponent; // Otherwise, Print "x^exponent"
}
}
else if (poly.next.exponent == 1) {
polynomialString = polynomialString + poly.next.coefficient + "x"; // Print "coefficientx"
}
else if (poly.next.exponent == 0) { // Print the Coefficient Alone...
polynomialString = polynomialString + poly.next.coefficient;
}
else { // Proceed Normally (WITH Coefficient & Exponent)
polynomialString = polynomialString + poly.next.coefficient + "x^" + poly.next.exponent;
}
poly = poly.next;
firstTerm = false;
}
return polynomialString;
}
// Create the addTerm() Method that Incorporates the Term "Coefficient * x^Exponent" to the Respective Polynomial (Needs Help)
public void addTerm(int coefficient, int exponent) {
if (exponent < 0) { // Polynomials CANNOT Have Coefficients with Negative Exponents
throw new IllegalArgumentException("Coefficients in polynomials must have positive exponents for use in our program. Thanks!");
}
Term newTerm = new Term(coefficient, exponent);
Term p = poly;
while (p.next != null && p.next.exponent > exponent) {
p = p.next;
}
newTerm.next = p.next;
p.next = newTerm;
}
// Create the eval() Method that Returns the Result of Evaluating the Polynomial at x = val (USE Horner's Method for this Method)
public double eval(double val) {
double result = 0;
Term p = poly;
p = p.next;
result += p.coefficient * val + p.next.coefficient;
p = p.next;
while (p.next != null) {
result = result * val + p.next.coefficient;
p = p.next;
}
return result;
}
// Create the multiply() Method that Returns a NEW Polynomial After Multiplying Each Term by the scalar Variable
public Polynomial multiply(int scalar) {
Polynomial newPoly = new Polynomial();
Term p = poly.next;
while (p.next != null) {
newPoly.addTerm(scalar * p.coefficient, p.exponent); // Multiplying the Coefficients and Scalar Together
p = p.next;
}
return newPoly;
}
// Create the add(Polynomial rhs) Method that Returns the Result of ADDING the "rhs" polynomial to "this" polynomial
public Polynomial add(Polynomial rhs) {
Polynomial newPoly = new Polynomial();
Term p1 = poly.next; // this polynomial
Term p2 = rhs.poly.next; // rhs polynomial
while (p1.next != null && p2.next != null) {
if (p1.exponent == p2.exponent) { // Same Exponents?
newPoly.addTerm(p1.coefficient + p2.coefficient, p1.exponent);
p1 = p1.next;
p2 = p2.next;
}
else if (p1.exponent > p2.exponent) { // Greater than rhs Polynomial?
newPoly.addTerm(p1.coefficient, p1.exponent);
p1 = p1.next;
}
else { // Less than rhs Polynomial?
newPoly.addTerm(p2.coefficient, p2.exponent);
p2 = p2.next;
}
}
if (p1.next == null) {
while (p2.next != null) { // Does the rhs Polynomial have Extra Terms?
newPoly.addTerm(p2.coefficient, p2.exponent);
p2 = p2.next;
}
}
if (p2.next == null) {
while (p1.next != null) { // Does the this Polynomial have Extra Terms?
newPoly.addTerm(p1.coefficient, p1.exponent);
p1 = p1.next;
}
}
return newPoly;
}
// Create the multiply(Polynomial rhs) Method that Returns the Result of MULTIPLYING the "rhs" polynomial to "this" polynomial
public Polynomial multiply(Polynomial rhs) {
Polynomial newPoly = new Polynomial();
Term p1 = poly.next; // this polynomial
Term p2 = rhs.poly.next; // rhs polynomial
while (p1.next != null) {
while (p2.next != null) {
newPoly.addTerm(p1.coefficient * p2.coefficient, p1.exponent + p2.exponent);
p2 = p2.next;
}
p1 = p1.next;
}
return newPoly;
}
It seems that this calculator works for all other cases, except cases like this:
(2*3^4)
It does not return 162, instead, it returns 0.0.
I identified that the error must be from the method public static double operation, since the default return statement is 0.0
Here is the code:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StackC<Item> implements Stack<Item> {
private Item[] a; // array of items
private int N; // number of elements on stack
public StackC() {
a = (Item[]) new Object[2];
}
public boolean isEmpty() {
return N == 0;
}
public int size() {
return N;
}
private void resize(int capacity) {
assert capacity >= N;
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < N; i++) {
temp[i] = a[i];
}
a = temp;
}
public void push(Item item) {
if (N == a.length) resize(2*a.length); // double size of array if necessary
a[N++] = item; // add item
}
public Item pop() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
Item item = a[N-1];
a[N-1] = null; // to avoid loitering
N--;
// shrink size of array if necessary
if (N > 0 && N == a.length/4)
resize(a.length/2);
return item;
}
public Item peek() {
if (isEmpty())
throw new NoSuchElementException("Stack underflow");
return a[N-1];
}
public Iterator<Item> iterator() {
return new ReverseArrayIterator();
}
private class ReverseArrayIterator implements Iterator<Item> {
private int i;
public ReverseArrayIterator() {
i = N;
}
public boolean hasNext() {
return i > 0;
}
public void remove() {
throw new UnsupportedOperationException();
}
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
return a[--i];
}
}
//---------------------------------------------------------------------
public static void main(String[] args) {
StackC<String> Operator = new StackC<String>();
StackC<Double> Values = new StackC<Double>();
while (!StdIn.isEmpty()) {
String token = StdIn.readString();
try {
Double x = Double.parseDouble(token);
Values.push(x);
}
catch(NumberFormatException nFE) {
}
if (token.equals("("))
Operator.push(token);
if (token.equals(")"))
{
if (Operator.peek() != "(")
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
Operator.pop();
}
if(token.equals("*") || token.equals("+") || token.equals("/") || token.equals("-") || token.equals("^") )
{
if(!Operator.isEmpty())
{
String prev = Operator.peek();
int x = comparePrecedence(token, Operator.peek()); // You need to compare precedence first
if(x == -1 || x == 0)
{
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
}
Operator.push(token);
}
}
while(!Operator.isEmpty())
{
String prev = Operator.peek();
String type = Operator.pop();
double b = Values.pop();
double a = Values.pop();
Values.push(operation(type,a,b));
}
System.out.println(Values.pop());
}
public static double operation(String operator, double a, double b) {
if (operator.equals("+"))
return a + b;
else if (operator.equals("-"))
return a - b;
else if (operator.equals("*"))
return a * b;
else if (operator.equals("/"))
return a / b;
else if (operator.equals("^"))
return Math.pow(a,b);
return 0.0;
}
public static int comparePrecedence(String x, String y)
{
int val1 = 0;
int val2 = 0;
if(x.equals("-"))
val1 = 0;
if(y.equals("-"))
val2 = 0;
if(x.equals("+"))
val1 = 1;
if(y.equals("+"))
val2 = 1;
if(x.equals("/"))
val1 = 2;
if(y.equals("/"))
val2 = 2;
if(x.equals("*"))
val1 = 3;
if(y.equals("*"))
val2 = 3;
if(x.equals("^"))
val1 = 4;
if(y.equals("^"))
val2 = 4;
if(val1 > val2)
return 1;
else if(val2 > val1)
return -1;
else
return 0;
}
}
Everything above the dotted line was given via the professor, and is not the problem for the code.
StdIn is simply a method that reads inputs.
I have a question to complete using Java Polynomials. I've set up all my code and it looks to be ok but with my composite method I receive a different output than is expected.
class Polyonmial
{
final static private int mantissa=52;
final static private double epsilon=Math.pow(2.0,-mantissa);
private double coefficient=0.0;
private int power=0;
private Polynomial successor=null;
public Polynomial(double coefficient, int power)
{
if (Double.isNaN(coefficient)) return;
if (Math.abs(coefficient)<epsilon) return;
if (power<0) return;
this.coefficient=coefficient;
this.power=power;
}
final public double coefficient(int power)
{
if (power<0) return 0.0;
Polynomial traverser=this;
do
{
if (traverser.power<power) return 0.0;
if (traverser.power==power) return traverser.coefficient;
traverser=traverser.successor;
}
while (traverser!=null);
return 0.0;
}
final public Polynomial composite(Polynomial that)
{
if (that==null) return null;
Polynomial thisClone = this.clone();
Polynomial thatClone = that.clone();
Polynomial temp = new Polynomial(0.0,0);
Polynomial result = new Polynomial(0.0,0);
while(thisClone != null)
{
if (thisClone.power == 0)
{
temp.coefficient = 1.0;
temp.power = 0;
}
else
{
if (thisClone.power == 1)
temp = thatClone;
}
//System.out.println("temp:"+temp);
while(temp != null)
{
temp.coefficient = thisClone.coefficient*temp.coefficient;
result = result.plus(temp);
temp = temp.successor;
}
temp = new Polynomial(0.0,0);
thisClone=thisClone.successor;
}
return result;
}
final public Polynomial[] dividedBy(Polynomial that)
{
if (that==null) return null;
if (that.coefficient==0.0) return null;
Polynomial quotient=new Polynomial(0.0,0);
Polynomial remainder=this.clone();
Polynomial traverser = this.clone();
Polynomial resultoftemp = new Polynomial(0.0, 0);
Polynomial temp = new Polynomial(0.0, 0);
double thiscoffe = this.coefficient(this.degree());
double thatcoffe = that.coefficient(that.degree());
if(that.coefficient !=0 && that.power !=0)
{
quotient.coefficient = thatcoffe / thiscoffe;
quotient.power = that.power - this.power;
}
while(traverser !=null)
{
temp.power = quotient.power + traverser.power;
temp.coefficient = quotient.coefficient * traverser.coefficient;
traverser=traverser.successor;
resultoftemp = resultoftemp.plus(temp);
remainder = that.minus(resultoftemp);
}
Polynomial[] result=new Polynomial[2];
result[0]=quotient;
result[1]=remainder;
return result;
}
final public Polynomial integrate()
{
if (this.coefficient==0.0) return new Polynomial(0.0,0);
Polynomial result=this.clone();
Polynomial temp = new Polynomial(0.0, 0);
Polynomial rstemp = new Polynomial(0.0, 0);
while(result!=null)
{
rstemp.power = result.power + 1;
rstemp.coefficient = result.coefficient / (result.power +1);
result = result.successor;
temp = temp.plus(rstemp);
}
return result;
}
final public Polynomial minus(Polynomial that)
{
if (that==null) return null;
if (this.equals(that)) return new Polynomial(0.0,0);
Polynomial result=this.clone();
if (that.coefficient==0.0) return result;
Polynomial traverser=that;
do
{
add(result,-traverser.coefficient,traverser.power);
traverser=traverser.successor;
}
while (traverser!=null);
return result;
}
final public int powerMax()
{
int max=Integer.MIN_VALUE;
Polynomial traverser=this;
do
{
if (max<traverser.power) max=traverser.power;
traverser=traverser.successor;
}
while (traverser!=null);
return max;
}
final public int powerMin()
{
int min=Integer.MAX_VALUE;
Polynomial traverser=this;
do
{
if (min>traverser.power) min=traverser.power;
traverser=traverser.successor;
}
while (traverser!=null);
return min;
}
}
In my expected output file I am supposed to receive this:
(-1.0*X^1+1.0).composite(-1.0*X^1+1.0)=
1.0*X^1
But instead I receive:
(-1.0*X^1+1.0).composite(-1.0*X^1+1.0)=
1.0*X^1+1.0
Any tips or help is greatly appreciated.
I have slightly changed your composite method as so (logically equivalent, brace moves and println additions):
final public Polynomial composite(Polynomial that) {
if (that==null) return null;
Polynomial thisClone = this.clone();
Polynomial thatClone = that.clone();
Polynomial temp = new Polynomial(0.0,0);
Polynomial result = new Polynomial(0.0,0);
while(thisClone != null) {
System.out.println("composite with term degree: " + thisClone.power);
if (thisClone.power == 0) {
temp.coefficient = 1.0;
temp.power = 0;
} else if (thisClone.power == 1) {
temp = thatClone;
} else {
for(int i=2; i<=thisClone.power; i++) {
temp = temp.plus(thatClone.times(thatClone));
}
}
System.out.println("temp heading in: " + temp);
while(temp != null) {
temp.coefficient = thisClone.coefficient*temp.coefficient;
result = result.plus(temp);
temp = temp.successor;
}
System.out.println("result so far: " + result);
temp = new Polynomial(0.0,0);
thisClone=thisClone.successor;
}
return result;
}
and for the example (-1.0*X^1+1.0).composite(-1.0*X^1+1.0), this is the output:
composite with term degree: 1
temp heading in: -1.0*X^1+1.0
result so far: 1.0*X^1
composite with term degree: 0
temp heading in: 1.0
result so far: 1.0*X^1+1.0
Am I correct to believe that the first "result so far" should be "-1.0*X^1-1.0"?
If so, let's examine the loop:
while(temp != null) {
temp.coefficient = thisClone.coefficient*temp.coefficient;
result = result.plus(temp);
temp = temp.successor;
}
I think this is your problem: result = result.plus(temp) is adding not just the "current term" to temp, but also the successor term. But then you loop on temp by setting it equal to its successor and do it again!
I think the solution is something like this (first calculate all temp terms, then update result):
Polynomial looptemp = temp;
while(looptemp != null) {
looptemp.coefficient = thisClone.coefficient*looptemp.coefficient;
looptemp = looptemp.successor;
}
result = result.plus(temp);
At the very least, it works for the single example I tried.
I need to add two polynomials together using a recursive method.
This is for a past-due assignment (I imagine a similar thing will be on a test).
Main class:
public class Polynomial {
private Node poly;
public Polynomial(){
poly = new Node();
}
private Polynomial(Node node){
poly = node;
}
public void addTerm(int coef, int exp){
Term term = new Term(coef, exp);
Node node = new Node(term, null);
Node iterator = poly;
//if the list is empty just add the node
if (poly.next == null){
System.out.println("poly.next is null. adding node to first pos.");
poly.next = node;
return;
}
//if list isn't empty find the appropriate spot for it
while (iterator.next != null){
System.out.println("iterator.next != null...");
if (exp < iterator.next.data.exp){
System.out.println("\texp < iterator.next.data.exp");
node.next = iterator.next;
iterator.next = node;
return;
}
if (exp == iterator.next.data.exp){
System.out.println("\texp == iterator.next.data.exp");
iterator.next.data.coef += coef;
return;
}
iterator = iterator.next;
}
//if we get to this point then the list isn't empty
//and it doesn't fit inside the list, hence it must
//be added to the end of the list
System.out.println("list wasn't empty, didn't fit inside");
iterator.next = node;
return;
}
#Override
public String toString(){
Node iterator = poly;
String out = "";
if (poly.next == null){
return out;
}
while(iterator.next != null){
out += iterator.next.data.coef;
out += "*x^";
out += iterator.next.data.exp;
out += " + ";
iterator = iterator.next;
}
return out.substring(0, out.lastIndexOf('+'));
}
public Polynomial addPolynomial (Polynomial that){
Polynomial ret = new Polynomial();
Polynomial iterator = this;
return addPolynomial(that, ret, iterator);
}
public Polynomial addPolynomial(Polynomial that, Polynomial ret, Polynomial iterator){
if (iterator.poly.next == null){
return new Polynomial(that.poly);
}
if (that.poly.next == null){
return new Polynomial(iterator.poly);
}
if (iterator.poly.next.data.exp < that.poly.next.data.exp){
ret.addTerm(iterator.poly.next.data.coef, iterator.poly.next.data.exp);
iterator.poly = iterator.poly.next;
return iterator.addPolynomial(that);
}
if (iterator.poly.next.data.exp == that.poly.next.data.exp){
ret.addTerm(iterator.poly.next.data.coef + that.poly.next.data.coef, iterator.poly.next.data.exp);
iterator.poly = iterator.poly.next;
that.poly = that.poly.next;
return iterator.addPolynomial(that);
}
if (iterator.poly.next.data.exp > that.poly.next.data.exp){
ret.addTerm(that.poly.next.data.coef, that.poly.next.data.exp);
that.poly = that.poly.next;
return iterator.addPolynomial(that);
}
return ret;
}
/*
* Term
*/
private class Term implements Comparable{
int coef;
int exp;
public int getCoef() {
return coef;
}
public void setCoef(int coef) {
this.coef = coef;
}
public int getExp() {
return exp;
}
public void setExp(int exp) {
this.exp = exp;
}
public Term(int coef, int exp) {
this.coef = coef;
this.exp = exp;
}
public int compareTo(Object rhs){
Term that = (Term)rhs;
return this.exp - that.exp;
}
}//end Term
/*
* Node
*/
private class Node{
Term data;
Node next;
public Term getData() {
return data;
}
public void setData(Term data) {
this.data = data;
this.next = null;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node() {
this.data = null;
this.next = null;
}
public Node(Term data, Node next) {
this.data = data;
this.next = next;
}
}//end Node
}
Test Class:
public class Polynomials {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
Polynomial p0 = new Polynomial();
p1.addTerm(1, 2);
p1.addTerm(1, 4);
p1.addTerm(1, 6);
p2.addTerm(1, 1);
p2.addTerm(1, 3);
p2.addTerm(1, 5);
System.out.println("p1 = " + p1.toString());
System.out.println("p2 = " + p2.toString());
System.out.println("Adding p1 to p2...");
p0 = p1.addPolynomial(p2);
System.out.println(p0.toString());
}
}
Have you considered this way of doing it?
public class Polynomial {
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
Polynomial p2 = new Polynomial();
Polynomial p0 = new Polynomial();
p1.addTerm(1, 2);
p1.addTerm(1, 4);
p1.addTerm(1, 6);
p2.addTerm(1, 1);
p2.addTerm(2, 3);
p2.addTerm(2, 2);
p2.addTerm(1, 5);
System.out.println("p1 = " + p1.toString());
System.out.println("p2 = " + p2.toString());
System.out.println("Adding p1 to p2...");
p0 = p1.addPolynomial(p2);
System.out.println(p0.toString());
for(int i = 0;i < 100;i++) {
p1 = new Polynomial();
p2 = new Polynomial();
for(int j = 0;j < 4;j++) {
p1.addTerm((int) (10 * Math.random()) - 5,
(int) (4 * Math.random()));
p2.addTerm((int) (10 * Math.random()) - 5,
(int) (4 * Math.random()));
}
p0 = p1.addPolynomial(p2);
System.out.println(p1 + "\n" + p2 + "\n" + p0 + "\n");
}
}
enum Comp {
LT, EQ, GT
}
static Comp cmp(int a, int b) {
return (a < b) ? Comp.LT : (a == b) ? Comp.EQ : Comp.GT;
}
private Term poly;
public Polynomial() {
poly = null;
}
public void addTerm(int coef, int exp) {
if (coef == 0) return;
Term term = new Term(coef, exp,null);
if (poly == null) {
poly = term;
} else {
poly = poly.add(term);
}
}
#Override
public String toString() {
if (poly == null) return "0";
StringBuilder buf = new StringBuilder();
poly.writeTo(buf);
return buf.toString();
}
public Polynomial addPolynomial(Polynomial that) {
Polynomial ret = new Polynomial();
if (poly != null) {
ret.poly = new Term(poly);
if (that.poly != null) {
ret.poly = ret.poly.add(new Term(that.poly));
}
} else if (that.poly != null) {
ret.poly = new Term(that.poly);
}
return ret;
}
private class Term {
final int coef;
final int exp;
final Term next;
Term(int coef, int exp, Term next) {
this.coef = coef;
this.exp = exp;
this.next = next;
}
Term(Term copy) {
this.coef = copy.coef;
this.exp = copy.exp;
if (copy.next == null) {
this.next = null;
} else {
this.next = new Term(copy.next);
}
}
Term add(Term other) {
if (other == null) return this;
switch (cmp(this.exp, other.exp)) {
case LT: {
Term n = other.add(this);
return n;
}
case GT: {
if (next == null) {
return new Term(coef,exp,other);
}
return new Term(coef,exp,next.add(other));
}
default: {
Term n = (next==null) ? other.next : next.add(other.next);
int nc = coef+other.coef;
return (nc!=0) ? new Term(nc,exp,n) : n;
}
}
}
public void writeTo(StringBuilder app) {
if (coef != 1 || exp == 0) app.append(coef);
if (exp == 1) {
app.append("x");
} else if (exp != 0) {
app.append("x^").append(exp);
}
if (next != null) {
app.append('+');
next.writeTo(app);
}
}
}
}
Well that's certainly a bit more complex than necessary.
So you want to add a Polynomial to an already existing one, i.e.:
4*x^2 + 4 to 5*x^4+x+5, which results in: 5*x^4+4*x^2+x+9
You could obviously simplify the problem quite a bit by just using an array, but it's also not that hard with a linked list, the code should look something like this:
You have two pointers one pointing to the current position in the polynomial we want to add values (term1) and another one in the one we want to add (term2), both initialized to the lowest entry in the linked list (which we assume is sorted according to the exponent).
while term1 != NULL && term2 != NULL do:
term1 > term2:
add term2 to list
term2 = term2.next()
term2 > term1:
term1 = term1.next()
term1 = term2:
add term2 to term1
term1 = term1.next()
term2 = term2.next()
while term1 == NULL && term2 != NULL:
add term2
term2 = term2.next()
You can easily adapt that to also create a new polynomial instead of adding one to the other.
Okay so a little bit more details on how to turn the iterative solution into a recursive one:
The first thing you always have to do when thinking about recursion is your exit condition.
In this case if you think about that's easy: We only do work as long as term2 is not NULL, as soon as term2 is NULL we're finished.
The next step is thinking about a good method signature and that's also quite easy this time, since we only need the two terms, so you can just use the two iterators:
void addTogether(Iterator term1, Iterator term2); (assuming you're using an interface that's similar to the ListIterator, since you need to insert at the position before term1 - there are several ways to implement that)
ANd now you've just got to get rid of the while loops and replace them with a recursive call (in which you distinguish the different cases, do the necessary action and call it again)
My add method works, however when I create a new SparsePolynomial object (at the bottom of the add method), the value of the newSparePolynomial changes when I debug it and I can't figure out where the extra information is coming from. Can someone help me?
Here is a copy of my code:
import java.util.ArrayList;
public class SparsePolynomial {
private ArrayList<Polynomial> polynomialarraylist = new ArrayList<Polynomial>();
/**
* Constructor to get values of an arraylist of integers
* #param arraylist that contains the integer values used for the polynomials
*/
public SparsePolynomial(ArrayList<Integer> arrayList)
{
//MODIFIDED: polynomialarraylist
//EFFECT: constructs the arraylist of polynomials based off the arraylist of integers
insertIntoPolynomialArray(arrayList);
}
/**
* Converts the elements of the integer array into polynomials
* #param arrayList that contains the polynomials contents
*/
private void insertIntoPolynomialArray(ArrayList<Integer> arrayList)
{
//MODIFIED: polynomialarray
//EFFECT: inputs the values of the arrayList into the polynomial array based on the position of the digits
for(int i = 0; i < arrayList.size(); i++)
{
Polynomial polynomial = new Polynomial(arrayList.get(i), arrayList.get(i+1));
polynomialarraylist.add(polynomial);
System.out.println("coef" + arrayList.get(i));
System.out.println("degree" + arrayList.get(i+1));
i++;
}
}
/**
*
*/
#Override
public String toString()
{
String result = "";
sort();
if (getDegree(0) == 0)
return "" + getCoefficient(0);
if (getDegree(0) == 1)
return getCoefficient(0) + "x + " + getCoefficient(0);
result = getCoefficient(0) + "x^" + getDegree(0);
for (int j = 1; j < polynomialarraylist.size(); j++)
{
if(j > polynomialarraylist.size())
{
break;
}
if
(getCoefficient(j) == 0) continue;
else if
(getCoefficient(j) > 0) result = result+ " + " + ( getCoefficient(j));
else if
(getCoefficient(j) < 0) result = result+ " - " + (-getCoefficient(j));
if(getDegree(j) == 1) result = result + "x";
else if (getDegree(j) > 1) result = result + "x^" + getDegree(j);
}
return result;
}
/**
* Sorts array
* #param array to sort
*/
private void sort()
{
ArrayList<Polynomial> temp = polynomialarraylist;
ArrayList<Polynomial> temp2 = new ArrayList<Polynomial>();
int polydegreemain = polynomialarraylist.get(0).degree();
temp2.add(polynomialarraylist.get(0));
for(int i = 1; i < polynomialarraylist.size(); i++)
{
if(i > polynomialarraylist.size())
{
break;
}
int polydegreesecondary = polynomialarraylist.get(i).degree();
if(polydegreemain < polydegreesecondary)
{
temp.set(i-1, polynomialarraylist.get(i));
temp.set(i, temp2.get(0));
}
}
polynomialarraylist = temp;
}
/**
* Makes object hashable
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((polynomialarraylist == null) ? 0 : polynomialarraylist
.hashCode());
return result;
}
/**
* Checks for equality of two objects
*/
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SparsePolynomial other = (SparsePolynomial) obj;
if (polynomialarraylist == null) {
if (other.polynomialarraylist != null)
return false;
} else if (!polynomialarraylist.equals(other.polynomialarraylist))
return false;
return true;
}
public boolean equals(SparsePolynomial Sparse)
{
if(this == Sparse)
{
return true;
}
else
{
return false;
}
}
public SparsePolynomial add(SparsePolynomial other)
{
ArrayList<Polynomial> thisPolynomial = createPolynomial();
SparsePolynomial newSparsePolynomial;
ArrayList<Polynomial> otherPolynomial = other.createPolynomial();
Polynomial oldsum = new Polynomial();
Polynomial newsum = new Polynomial();
for(int i = 0; i < thisPolynomial.size();i++)
{
if(thisPolynomial.size() == 1)
{
newsum = thisPolynomial.get(i);
oldsum = newsum;
break;
}
if(i == 0)
{
newsum = thisPolynomial.get(i).add(thisPolynomial.get(i+1));
oldsum = newsum;
i++;
}
else
{
newsum = oldsum.add(thisPolynomial.get(i));
oldsum = newsum;
}
}
for(int i = 0; i < otherPolynomial.size(); i++)
{
newsum = oldsum.add(otherPolynomial.get(i));
oldsum = newsum;
}
ArrayList<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < oldsum.degree()+1; i++)
{
ints.add(oldsum.coefficient(i));
ints.add(i);
}
newSparsePolynomial = new SparsePolynomial(ints);
return newSparsePolynomial;
}
public SparsePolynomial subtract(SparsePolynomial other)
{
ArrayList<Polynomial> thisPolynomial = createPolynomial();
ArrayList<Polynomial> otherPolynomial = other.createPolynomial();
Polynomial olddifference = new Polynomial();
Polynomial newdifference = new Polynomial();
for(int i = 0; i < thisPolynomial.size()+1;i++)
{
if(i == 0)
{
newdifference = thisPolynomial.get(i).subtract(thisPolynomial.get(i+1));
olddifference = newdifference;
i++;
}
else
{
newdifference = olddifference.subtract(thisPolynomial.get(i));
olddifference = newdifference;
}
}
for(int i = 0; i < otherPolynomial.size(); i++)
{
newdifference = olddifference.add(otherPolynomial.get(i));
olddifference = newdifference;
}
ArrayList<Polynomial> polyarray = createArrayListOfPolynomialsFromPolynomials(olddifference);
ArrayList<Integer> ints = new ArrayList<Integer>();
for(int i = 0; i < polyarray.size(); i++)
{
ints.add(polyarray.get(i).coefficient(polyarray.get(i).degree()));
ints.add(polyarray.get(i).degree());
}
SparsePolynomial newSparsePolynomial = new SparsePolynomial(ints);
return newSparsePolynomial;
}
private int getDegree(int index)
{
int degree;
degree = polynomialarraylist.get(index).degree();
return degree;
}
private int getCoefficient(int index)
{
int coefficient;
coefficient = polynomialarraylist.get(index).coefficient(polynomialarraylist.get(index).degree());
return coefficient;
}
private ArrayList<Polynomial> createPolynomial()
{
Polynomial polynomial = null;
ArrayList<Polynomial> polynomialArray = new ArrayList<Polynomial>();
for(int i = 0; i < polynomialarraylist.size(); i++)
{
polynomial = new Polynomial(getCoefficient(i), getDegree(i));
polynomialArray.add(polynomial);
}
return polynomialArray;
}
Polynomial class
public class Polynomial {
// Overview: ...
private int[] terms;
private int degree;
// Constructors
public Polynomial() {
// Effects: Initializes this to be the zero polynomial
terms = new int[1];
degree = 0;
}
public Polynomial(int constant, int power) {
// Effects: if n < 0 throws IllegalArgumentException else
// initializes this to be the polynomial c*x^n
if(power < 0){
throw new IllegalArgumentException("Polynomial(int, int) constructor");
}
if(constant == 0) {
terms = new int[1];
degree = 0;
return;
}
terms = new int[power+1];
for(int i=0; i<power; i++) {
terms[i] = 0;
}
terms[power] = constant;
degree = power;
}
private Polynomial(int power) {
terms = new int[power+1];
degree = power;
}
// Methods
public int degree() {
// Effects: Returns the degree of this, i.e., the largest exponent
// with a non-zero coefficient. Returns 0 is this is the zero polynomial
return degree;
}
public int coefficient(int degree) {
// Effects: Returns the coefficient of the term of this whose exponent is degree
if(degree < 0 || degree > this.degree) {
return 0;
}
else {
return terms[degree];
}
}
public Polynomial subtract(Polynomial other) throws NullPointerException {
// Effects: if other is null throws a NullPointerException else
// returns the Polynomial this - other
return add(other.minus());
}
public Polynomial minus() {
// Effects: Returns the polynomial - this
Polynomial result = new Polynomial(degree);
for(int i=0; i<=degree; i++) {
result.terms[i] = -this.terms[i];
}
return result;
}
public Polynomial add(Polynomial other) throws NullPointerException {
// Effects: If other is null throws NullPointerException else
// returns the Polynomial this + other
Polynomial larger, smaller;
if (degree > other.degree){
larger = this;
smaller = other;
}
else {
larger = other;
smaller = this;
}
int newDegree = larger.degree;
if (degree == other.degree) {
for(int k = degree; k > 0 ; k--) {
if (this.terms[k] + other.terms[k] != 0) {
break;
}
else {
newDegree --;
}
}
}
Polynomial newPoly = new Polynomial(newDegree);
int i;
for (i=0; i <= smaller.degree && i <= newDegree; i++){
newPoly.terms[i] = smaller.terms[i] + larger.terms[i];
}
for(int j=i; j <= newDegree; j++) {
newPoly.terms[j] = larger.terms[j];
}
return newPoly;
}
public Polynomial multiply(Polynomial other) throws NullPointerException {
// Effects: If other is null throws NullPointerException else
// returns the Polynomial this * other
if ((other.degree == 0 && other.terms[0] == 0) ||
(this.degree==0 && this.terms[0] == 0)) {
return new Polynomial();
}
Polynomial newPoly = new Polynomial(degree + other.degree);
newPoly.terms[degree + other.degree] = 0;
for(int i=0; i<=degree; i++) {
for (int j=0; j<= other.degree; j++) {
newPoly.terms[i+j] = newPoly.terms[i+j] + this.terms[i] * other.terms[j];
}
}
return newPoly;
}
At quick glance, looks like this is a problem
for(int i = 0; i < arrayList.size(); i++)
{
Polynomial polynomial = new Polynomial(arrayList.get(i), arrayList.get(i+1));
polynomialarraylist.add(polynomial);
System.out.println("coef" + arrayList.get(i));
System.out.println("degree" + arrayList.get(i+1));
i++;
}
You're doing i++ twice here.
Also, you posted WAY too much code. No one wants to read that much. You're just lucky that, assuming this is the problem, I happened to glance at that.
Also that will throw an arrayindexoutofboundserror since you're doing .get(i+1)
the constructor is set up the way it is because the get(i) gets you the coefficient and the i+1 gets you the degree from the arraylist parameter since when you call add, without those the arraylist contents would be off
THe constructor is suppose to take an Arraylist and put them inisde of an arraylist of polynomials. using the odds as the coefficient and the evens as the degrees of the polynomials.