cox.jmatt.java.MathTools
Class Polynomial

java.lang.Object
  extended by cox.jmatt.java.MathTools.Polynomial

public class Polynomial
extends java.lang.Object

This class encapsulates polynomial behavior. It provides methods to add, subtract and multiply polynomials. Once created a Polynomial is immutable. Only the names of the variable and the function have setters and they do not affect the actual polynomial, only its presentation.

One critical aspect to using Polynomial is understanding its formatting String. At its heart this String lists the polynomial coefficients from left to right IN DESCENDING ORDER! So the String '1 0 3 -6' would be the polynomial x^3 + 3x - 6'. To specify the variable to use when formatting the Polynomial, prefix it to the format String followed by a colon. E.g. the polynomial cited above would be: 'x:1 0 3 -6'. Finally, to specify the name of the function used when formatting in function notation, precede the variable with the name of the function followed by a colon. So, 'P:z:2 6 9' would, if expressed using function notation, be 'P(z) = 2z^2 + 6z + 9'. Both the variable and function names are optional, but if only one is present it is taken to be the variable. So, to specify a function name in the format String you must also specify the variable name.


Field Summary
static java.lang.String FORMAT_LATEX
          LaTeX term format.
static java.lang.String FORMAT_OO_TYPICAL
          Typical Polynomial format using makeFormatTokens() tokens, OpenOffice version.
static java.lang.String FORMAT_TYPICAL
          Typical Polynomial format using makeFormatTokens() tokens: <12> <8><13><17><14>.
 
Constructor Summary
Polynomial()
          The default constructor.
Polynomial(int[] pCoefs)
          Create a Polynomial from an int[] array.
Polynomial(Polynomial pPoly)
          Copy constructor.
Polynomial(java.lang.String pData)
          Construct a Polynomial from a createPloynomial() format String.
 
Method Summary
 Polynomial add(Polynomial pPoly)
          Add this to another Polynomial.
 int coefficient(int pPos)
          Return a single specific coefficient.
 int[] coefficients()
          Return a copy of the Polynomial's coefficients.
 Polynomial copyOf()
          Return a copy of this Polynomial.
static Polynomial createPolyKnobs(java.lang.String pData)
          Construct a random Polynomial using a KNOBS String.
static Polynomial createPolynomial(int[] coefs)
          Create an instance from an int array.
static Polynomial createPolynomial(java.lang.String pData)
          This method takes a specially-formatted String and converts it into a polynomial.
 java.lang.String dataString()
          This method generates the construction String used to create instances and in toString() and toXML().
 int degree()
          Return the degree (exponent of the highest term) of the Polynomial.
 Polynomial derivative()
          Calulate the first derivative of the Polynomial, because it is easy.
 boolean equals(Polynomial pRHP)
          This method provides a naive equality test for Polynomial instances.
 long evaluate(int pVal)
          Evaluate the current Polynomial for the given value.
 Polynomial evaluate(Polynomial pPoly)
          This method evaluates this Polynomial OF another Polynomial.
 java.lang.String format(boolean pAscending)
          Format this Polynomial per its internal format.
 java.lang.String format(java.lang.String pTerm, boolean pAscending, boolean pIncludeZero)
          This is the standard Polynomial formatting method.
static java.lang.String formatEquation(Polynomial pLHP, Polynomial pRHP, java.lang.String pRelation, java.lang.String lFence, java.lang.String rFence)
          This method creates a polynomial equation or inequality based on the two Polynomials sent in.
 java.lang.String formatNewEquation(Polynomial pLHP, Polynomial pRHP, java.lang.String pRelation, java.lang.String lFence, java.lang.String rFence)
          Instance shadow for creating equations.
 Question formatNewQuotient(Polynomial pQuotient, Polynomial pDivisor, java.lang.String pDivBy, java.lang.String lFence, java.lang.String rFence)
          Instance version of formatQuotient().
static Question formatQuotient(Polynomial pQuotient, Polynomial pDivisor, java.lang.String pDivBy, java.lang.String lFence, java.lang.String rFence)
          This method creates a rational expression whose numerator can be factored and reduced.
 java.lang.String[] formatTerms(java.lang.String pTerm)
          This method formats the terms of the Polynomial but returns them as a String array.
 java.lang.String getFName()
          Get the function name used for the Polynomial.
 java.lang.String getVariable()
          Get the variable used for the Polynomial.
static java.lang.String[] makeFormatTokens(int pCoef, int pExp, java.lang.String pVar, java.lang.String pFName, boolean isFirst)
          This method creates the formatting token array for the data supplied.
 java.lang.String makeFun(java.lang.String pExpr, java.lang.String pRelation)
          Super-convenience method to assemble function notation consisting of this Polynomial's name and variable or expression.
 Polynomial multiply(int pConst)
          Multiply the terms of this Polynomial by a constant.
 Polynomial multiply(Polynomial pPoly)
          Multiply this Polynomial by another.
 Polynomial newPolyKnobs(java.lang.String pData)
          This is the instance version of createPolyKnobs().
 Polynomial newPolynomial(int[] coefs)
          Instance version of createPolynomial(int[]).
 Polynomial newPolynomial(java.lang.String pData)
          This is the instance version of the static createPolynomial() method.
 java.lang.String printPolynomial(boolean pAscending, boolean pFunction)
          Express the Polynomial as a String.
static void setCaret(java.lang.String pNewCaret)
          The caret is the character used to designate an exponent.
static void setDefaultFormat(java.lang.String pFormat)
          Set the default term format for every Polynomial created after this one.
 Polynomial setFName(java.lang.String pNew)
          Set the name of the function used when this Polynomial is printed in function form.
 void setFormat(java.lang.String pFormat)
          Set the term format for this Polynomial.
 void setNewCaret(java.lang.String pNewCaret)
          Instance shadow.
 void setNewDefaultFormat(java.lang.String pFormat)
          Instance flavor of setDefaultFormat().
 Polynomial setVariable(java.lang.String pNew)
          Set the variable used for this polynomial.
 Polynomial subtract(Polynomial pPoly)
          Subtract another Polynomial from this one.
 java.lang.String toMathML(boolean pAscending, boolean pSmart)
          Format the Polynomial using MathML Presentation markup.
 java.lang.String toString()
          Overridden to provide a constructor-style representation of this Polynomial.
 java.lang.String toXML(java.lang.String pID)
          The toXML() method returns the Polynomial's data in a createPolynomial()-style XML String: <Polynomial data='F:V:Cn ...
 Polynomial truncate()
          This is the only method that can alter an already-created Polynomial.
 java.lang.String unFormat(java.lang.String pUnTemplate, boolean printOnes)
          This method provides a totally different way to format the Polynomial.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

FORMAT_TYPICAL

public static final java.lang.String FORMAT_TYPICAL
Typical Polynomial format using makeFormatTokens() tokens: <12> <8><13><17><14>.

See Also:
Constant Field Values

FORMAT_OO_TYPICAL

public static final java.lang.String FORMAT_OO_TYPICAL
Typical Polynomial format using makeFormatTokens() tokens, OpenOffice version.

See Also:
Constant Field Values

FORMAT_LATEX

public static final java.lang.String FORMAT_LATEX
LaTeX term format. All intelligence is applied: the lead coefficient is blank if +1, '-' if -1, visible otherwise; no exponent on first-degree or constant term; no variable on constant term.

See Also:
Constant Field Values
Constructor Detail

Polynomial

public Polynomial()
The default constructor. It returns the zero polynomial and is useful only for creating other Polynomials.


Polynomial

public Polynomial(int[] pCoefs)
Create a Polynomial from an int[] array. This array becomes the coefficients. If the array is null or of length zero the zero polynomial is created.

Parameters:
pCoefs - An int array containing the coefficients of the new Polynomial.

Polynomial

public Polynomial(java.lang.String pData)
Construct a Polynomial from a createPloynomial() format String.


Polynomial

public Polynomial(Polynomial pPoly)
Copy constructor. If pPoly is null the zero polynomial is created.

Method Detail

createPolynomial

public static Polynomial createPolynomial(java.lang.String pData)

This method takes a specially-formatted String and converts it into a polynomial. The format of the String is 'F:V:Cn Cn-1 ... C1 C0' where F is the name of the function, V is the variable, and Cn ... C0 is the space-separated list of coefficients. If any coefficient cannot be converted to int, it is replaced silently with 0. Both the function name and variable are optional; if there are only two components, however, they are assumed to be the variable and the coefficient list. If the format String is null or empty the zero Polynomial is returned.

This is a static factory method. It is the most common way to construct a Polynomial.

Parameters:
pData - The Polynomial data String.
Returns:
A freshly-constructed Polynomial.

newPolynomial

public Polynomial newPolynomial(java.lang.String pData)
This is the instance version of the static createPolynomial() method.


createPolynomial

public static Polynomial createPolynomial(int[] coefs)
Create an instance from an int array.


newPolynomial

public Polynomial newPolynomial(int[] coefs)
Instance version of createPolynomial(int[]).


copyOf

public Polynomial copyOf()
Return a copy of this Polynomial. All data is the same but the instances themselves are NOT!


createPolyKnobs

public static Polynomial createPolyKnobs(java.lang.String pData)
Construct a random Polynomial using a KNOBS String. The variable and function can be set per the standard Polynomial format string but the coefficients conponent is fed to MathEngine.setKnobs()!

Parameters:
pData - A Polynomial-compliant formatting string BUT with the coefficients interpreted as a MathEngine setKnobs() string.
Returns:
A Polynomial with random coefficients.

newPolyKnobs

public Polynomial newPolyKnobs(java.lang.String pData)
This is the instance version of createPolyKnobs().


truncate

public Polynomial truncate()
This is the only method that can alter an already-created Polynomial. It removes any leading zero coefficients and resizes the coefficient array. It returns a reference to this polynomial. Most methods that might generate extraneous zeros call this one automatically but it is here if needed.


getVariable

public java.lang.String getVariable()
Get the variable used for the Polynomial. The default is 'x.'


setVariable

public Polynomial setVariable(java.lang.String pNew)

Set the variable used for this polynomial. A null or blank value is ignored and the variable is set to the default ('x') OR the last variable set in any previous Polynomial. That is, setting the variable sets the new default value which remains until specifically changed. A self-reference is returned to allow method chaining.


getFName

public java.lang.String getFName()
Get the function name used for the Polynomial. The default is 'f.'


setFName

public Polynomial setFName(java.lang.String pNew)

Set the name of the function used when this Polynomial is printed in function form. Setting this to a non-null, non-empty value sets a new default value for all subsequent instances.


setCaret

public static void setCaret(java.lang.String pNewCaret)
The caret is the character used to designate an exponent. It defaults to '^' but can be changed. This method sets the default caret for all instances. If pNewCaret is null or blank it resets to '^'. This is the value used in the caret and smart caret formatting tokens; there is no per-instance caret.


setNewCaret

public void setNewCaret(java.lang.String pNewCaret)
Instance shadow.


dataString

public java.lang.String dataString()
This method generates the construction String used to create instances and in toString() and toXML().


formatTerms

public java.lang.String[] formatTerms(java.lang.String pTerm)

This method formats the terms of the Polynomial but returns them as a String array. From there custom formatting and arrangement can be performed. The replacement tokens are per the full format() method, all terms are included, and ascending/descending is not relevant. If pTerm is null or blank the default is used.

CRITICAL NOTE: This method has been updated to use makeFormatTokens() tokens.

Parameters:
pTerm - The formatting String to be used for each term.
Returns:
A String[] array consisting of the terms formatted per the template sent in.

format

public java.lang.String format(java.lang.String pTerm,
                               boolean pAscending,
                               boolean pIncludeZero)

This is the standard Polynomial formatting method. It is designed to format the Polynomial only, any 'decorations' must be added afterward. It may be printed in ascending or descending order and with zero terms included or omitted. The formatting tokens available are:

These are the tokens generated by makeFormatTokens() applied to this Polynomial.

Parameters:
pTerm - The formatting template for each term.
pAscending - True to print ascending, false for descending.
pIncludeZero - True to include zero terms, false to omit them.

makeFormatTokens

public static java.lang.String[] makeFormatTokens(int pCoef,
                                                  int pExp,
                                                  java.lang.String pVar,
                                                  java.lang.String pFName,
                                                  boolean isFirst)

This method creates the formatting token array for the data supplied. This is independent of any particular Polynomial instance so the arguments must be supplied each time. The tokens supplied are listed in the format() method.

Parameters:
pCoef - The term coefficient.
pExp - The term exponent.
pVar - The term variable. If null or blank a default is supplied.
pFName - The polynomial or function name. If null or blank a default is supplied.
isFirst - Flag to indicate the first term formatted regardless of 'direction.'

format

public java.lang.String format(boolean pAscending)

Format this Polynomial per its internal format. Zero terms are excluded.

CRITICAL NOTE: This method has been updated to use the new formatTokens() method.

Parameters:
pAscending - true to format in ascending order, false for descending.
Returns:
A freshly-formatted Polynomial.

formatQuotient

public static Question formatQuotient(Polynomial pQuotient,
                                      Polynomial pDivisor,
                                      java.lang.String pDivBy,
                                      java.lang.String lFence,
                                      java.lang.String rFence)

This method creates a rational expression whose numerator can be factored and reduced. It accepts a quotient and divisor and produces the dividend as the product of the two. It assumes both Polynomials sent in have formats set and it uses default formatting for the dividend. The 'lFence' and 'rFence' Strings are wrapped around all formatted Strings. The 'divBy' argument is placed between the dividend and the quotient with no spacing.

CRITICAL NOTE: This method has been updated to the new format() methods.

Parameters:
pQuotient - The quotient (answer!) Polynomial.
pDivisor - The divisor Polynomial.
lFence - Appended to all formatted Polynomials on the left side. Ignored if null or blank.
rFence - Appended to all formatted Polynomials on the right side. Ignored if null or blank.
pDivBy - Placed between the dividend Polynomial and the divisor. Default value is a single slash.

formatNewQuotient

public Question formatNewQuotient(Polynomial pQuotient,
                                  Polynomial pDivisor,
                                  java.lang.String pDivBy,
                                  java.lang.String lFence,
                                  java.lang.String rFence)
Instance version of formatQuotient().


formatEquation

public static java.lang.String formatEquation(Polynomial pLHP,
                                              Polynomial pRHP,
                                              java.lang.String pRelation,
                                              java.lang.String lFence,
                                              java.lang.String rFence)

This method creates a polynomial equation or inequality based on the two Polynomials sent in. The left-hand side of the relation is the sum of the two and the right-hand side is pRHP. If null or blank 'pRelation' defaults to '='. The fence characters are put around both formatted Strings and are ignored if null or blank. If either Polynomial is null the method returns null.

The original intent behind this method was to generate guaranteed-factorable polynomial equations with nonzero terms on each side. Its solvability depends on that of the 'pLHP' Polynomial.

Parameters:
pLHP - The left-hand Polynomial.
pRHP - The right-hand Polynomial.
pRelation - The relation to use. Defaults to equality.
lFence - Appended to both formatted Polynomials on the left.
rFence - Appended to both formatted Polynomials on the right.

formatNewEquation

public java.lang.String formatNewEquation(Polynomial pLHP,
                                          Polynomial pRHP,
                                          java.lang.String pRelation,
                                          java.lang.String lFence,
                                          java.lang.String rFence)
Instance shadow for creating equations.


makeFun

public java.lang.String makeFun(java.lang.String pExpr,
                                java.lang.String pRelation)
Super-convenience method to assemble function notation consisting of this Polynomial's name and variable or expression. The body of the polynomial is not included but an relation sign may be.

Parameters:
pExpr - The expression around which to build the function notation.
pRelation - The relation symbol to append to the finished notation, separated by a single space. Ignored if null or blank.

setFormat

public void setFormat(java.lang.String pFormat)
Set the term format for this Polynomial. Null or blank defaults to the default format.


setDefaultFormat

public static void setDefaultFormat(java.lang.String pFormat)
Set the default term format for every Polynomial created after this one. Null or blank defaults to FORMAT_TYPICAL.


setNewDefaultFormat

public void setNewDefaultFormat(java.lang.String pFormat)
Instance flavor of setDefaultFormat().


printPolynomial

public java.lang.String printPolynomial(boolean pAscending,
                                        boolean pFunction)
Express the Polynomial as a String. The Polynomial may be in ascending or descending order and printed using function notation or not. Despite its name this method does not present fancy formatting options. To convert to MathML or some other format, dump the coefficient array and perform the formatting manually. The array index of each term is its exponent.

Parameters:
pAscending - true for ascending order, false for descending order.
pFunction - true to use function notation, false for standard polynomial notation.

unFormat

public java.lang.String unFormat(java.lang.String pUnTemplate,
                                 boolean printOnes)

This method provides a totally different way to format the Polynomial. The argument is a standard template string BUT in this method the replacement tokens are the coefficients of the Polynomial: <0> is the constant term, <1> is the first-degree coefficient up to the degree of the entire Polynomial. This allows for easier generation of Polynomial expressions with out-of-order terms.

To facilitate custom construction of polynomial equations with nonzero terms on both sides this method (and ONLY this method) defines another set of replacement tokens. Placing a double minus ('--') in front of the number within the token reverses the sign of that term. That means <--2> is the opposite of the square coefficient.

Coefficients of '+1' may be printed or suppressed. The 'printOnes' argument controls this; send true to include them, false to replace them with ''.

If the template is null or blank it is returned unaltered.

Parameters:
pUnTemplate - The template to receive the coefficient array.
printOnes - True to print coefficients of 1, false to blank them.

toXML

public java.lang.String toXML(java.lang.String pID)
The toXML() method returns the Polynomial's data in a createPolynomial()-style XML String: <Polynomial data='F:V:Cn ... C1 C0' /> for easy parsing. The pID, if not null or empty, becomes an 'id=' attribute.

Parameters:
pID - The id attribute of the resulting XML tag. May be null or empty.

toString

public java.lang.String toString()
Overridden to provide a constructor-style representation of this Polynomial.

Overrides:
toString in class java.lang.Object

toMathML

public java.lang.String toMathML(boolean pAscending,
                                 boolean pSmart)
Format the Polynomial using MathML Presentation markup. This can be ascending or descending order and 'smart' or 'raw'. In 'raw' mode everything is present on every term. 'Smart' mode is exactly per smart mode on MathXML.formatMonomial(). Regardless of mode, <mrow> tags are added appropriately.

Parameters:
pAscending - true to print in ascending mode, false for descending.
pSmart - true for smart mode, false for raw mode.
Returns:
A MathML-formatted String of the Polynomial.

degree

public int degree()
Return the degree (exponent of the highest term) of the Polynomial.


coefficients

public int[] coefficients()
Return a copy of the Polynomial's coefficients.


coefficient

public int coefficient(int pPos)
Return a single specific coefficient. If the coefficient specified does not exist or the positon is negative, the return is 0.

Parameters:
pPos - The position of the coefficient to fetch.
Returns:
The coefficient at pPos.

equals

public boolean equals(Polynomial pRHP)
This method provides a naive equality test for Polynomial instances. Two polynomials test as equal if and only if they are of equal degree and all coefficients are equal. If 'pRHP' is null this method returns false immediately.

Parameters:
pRHP - The Polynomial to test for equality.
Returns:
false if 'pRHP' is null, true iff the degrees and the coefficients are equal.

add

public Polynomial add(Polynomial pPoly)
Add this to another Polynomial. Neither is changed; a copy is returned. If pPoly is null it is treated as the zero Polynomial. The variable and function name are of this Polynomial.

Parameters:
pPoly - The Polynomial to add to this one.
Returns:
The sum of the two Polynomials.

subtract

public Polynomial subtract(Polynomial pPoly)
Subtract another Polynomial from this one. Neither is changed; a copy is returned. If pPoly is null it is treated as the zero Polynomial. The variable and function name are of this Polynomial.

Parameters:
pPoly - The Polynomial to subtract from this one.
Returns:
The difference of the two Polynomials.

multiply

public Polynomial multiply(Polynomial pPoly)
Multiply this Polynomial by another. If the second Polynomial is null a copy of this one is returned.

Parameters:
pPoly - The Polynomial to multiply by this one.
Returns:
The product of the two Polynomials.

multiply

public Polynomial multiply(int pConst)
Multiply the terms of this Polynomial by a constant. If the scalar is zero, the zero Polynomial is returned. As with other methods, this one does not alter the Polynomial to which it is applied.

Parameters:
pConst - The int constant to multiply by the coefficients.

evaluate

public long evaluate(int pVal)
Evaluate the current Polynomial for the given value. Returned as a long to allow for evaluation.

Parameters:
pVal - The value at which to evaluate the Polynomial.
Returns:
The Polynomial evaluated at pVal.

evaluate

public Polynomial evaluate(Polynomial pPoly)
This method evaluates this Polynomial OF another Polynomial. This is useful for function composition. Neither of the operands is changed and the resulting Polynomial has its name set to the composition of the two names of the operands using a lowercase 'O' ('o') for the composition symbol. If the Polynomial sent in is null the return value is the zero Polynomial.

Parameters:
pPoly - The Polynomial to be substituted for the variable in this and evaluated.
Returns:
The composition of this Polynomial evaluated at pPoly, or the zero Polynomial if this one is null.

derivative

public Polynomial derivative()
Calulate the first derivative of the Polynomial, because it is easy. The original Polynomial is not changed. The function name is altered: it has a 'prime' mark (single quote) appended.