Search code examples
javajunitpolynomial-mathnegate

Java - Negate a polynomial


I am trying to negate a polynomial expression so that the following tests are correct with my polynomial expressions being defined as Term(coefficient, exponent). So my public Term negate() throws Overflow method passes these tests.

Term(min,2) -> expected = Overflow
Term(-7,2) -> expected = (7,2)
Term(0,2) -> expected = (0,2)
Term(7,2) -> expected = (-7,2)
Term(max,2) -> expected = (-max,2)

EDIT: I have the following method within Term:

public Term negate() throws Overflow {

}

and the following in the Term constructor:

public Term(int c, int e) throws NegativeExponent{
    if (e < 0) throw new NegativeExponent();
    coef = c;
    expo = (c == 0 && e != 0) ? 0 : e;
}

The tests above are in a seperate JUnit file, but I am trying to make the negate() method pass the tests.


Solution

  • I can only answer this because I answered one of your previous questions... so you might want to clarify a little more in your post.

    Perhaps you want

    public Term negate() throws Overflow, NegativeExponent {
        if (coef == min)
            throw new Overflow();
        return new Term(-coef, expo);
    }
    

    You might want to consider renaming Overflow to something more specific as well (so as to fully distinguish it from a StackOverflowError).