package poly; /** * Represents the constant polynomial type. * @author Dung X. Nguyen */ class ConstPoly extends APolynomial { /** * @param coef the constant coefficient for this ConstPoly. */ ConstPoly(double coef) { _coef = coef; } public int getDegree() { return 0; } /** * Throws NoSuchElementException. */ public APolynomial getLowerPoly() { throw new java.util.NoSuchElementException ("Constant polynomial has no lower order term!"); } /** * Passes _coef to p for p to add. */ public APolynomial add(APolynomial p) { return p.addConst (_coef); } /** * Returns the coefficient of this ConstPoly. */ public double eval(double x) { return _coef; } /** * Returns the coefficient of this ConstPoly. */ public double evalHorner (double x) { return _coef; } /** * Returns the String representation of the coefficient of this ConstPoly. */ public String toString () { return Double.toString(_coef); } /** * Called by an APolynomial that contains this ConstPoly as its lower order polynomial. * Returns the empty String if this ConstPoly is the zero polynomial, otherwise * returns " + " followed by the String representation of this ConstPoly's coefficient. */ protected String toString4LowerPoly () { return (0 == _coef)? "": " + " + Double.toString(_coef); } /** * Returns a ConstPoly whose coefficient is the sum of _coef with the double parameter. */ protected APolynomial addConst (double c) { return PolyFactory.MakeConstPoly (_coef + c); } /** * Terminates evalHornerHelp recursive call. Raises x to the power of the enclosing * higher order polynomial. Multiply it by the accumulated computed value. Add the * result to _coef and returns the sum. */ protected double evalHornerHelp (double x, double acc, int preDegree) { return acc * Math.pow (x, preDegree) + _coef; } /** * Divides _coef into the dividend APolynomial. * @throw IllegalArgumentException if _coef is zero. */ protected QRPair divmodInto(APolynomial dividend) { if (0.0 == _coef) { throw new IllegalArgumentException ("Divide by 0!"); } return new QRPair (dividend.multMonomial (1.0 / _coef, 0), PolyFactory.ZeroPoly); } /** * Returns a ConstPoly whose coefficient is the product of this _coef and the input coef, * if the input degree is zero, else returns APolynomial with coefficient coef * _coef, * order degree, and the zero polynomial as the lower order polynomial. */ protected APolynomial multMonomial (double coef, int degree) { return 0 == degree? PolyFactory.MakeConstPoly (coef * _coef): PolyFactory.MakePoly(coef * _coef, degree, PolyFactory.ZeroPoly); } }