|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Objectcox.jmatt.java.MathTools.MathEngine
public class MathEngine
This is the power-class of the MathTools package. It provides services to all other packages except Question and contains several powerful and flexible power-methods. It also contains a pseudorandom number generator that can be re-seeded dynamically to allow for 'deterministically random' numbers. Along with this is a re-seed method that takes its seed from the system clock, so 'more' randomness is also available. Even though all MEngine methods are static, a constructor is provided to allow exposure to scripts.
In addition to its mathematical methods, MathEngine
also contains equipment for working with Strings and parameter blocks. A parameter block
is a group of two or more parameters (Global Pizza) that share a common prefix and sequential numbers. The prefix must be identical on all elements
and the numbering must start at zero. I.e. topping.0 = cheese, topping.1 = onions, topping.2 = pepperoni, etc. Param block detection stops when an attempt to
retrieve a number fails, so numbers cannot be skipped.
The splick()
methods split a string into tokens and return one at random. The splickInt()
method does the same, but assumes a
space-separated String of ints and returns its choice as an int. The spill()
power-method breaks a String into an array, guarantees a minimum
length, and pads any 'leftover' elements with a designated fill value.
Field Summary | |
---|---|
static int |
MAX_PRIME
This is the maximum prime number available to the rPrime() methods: 1013. |
static java.lang.String |
MEM_PREFIX
This is the prefix attached to quantities stored from parseRPN() . |
Constructor Summary | |
---|---|
MathEngine()
Constructor provided to generate instances for scripting. |
Method Summary | |
---|---|
static void |
adjustRandom(double pPower,
double pRoot)
For ADVANCED USERS. |
static java.lang.String |
arCat(double[] pNums,
boolean pAnd,
boolean pWords)
Concatenate a double array into String, per arCat(int) . |
static java.lang.String |
arCat(int[] pNums,
boolean pAnd,
boolean pWords)
Concatenate an int array int String. |
static java.lang.String |
arCat(java.lang.String[] pAry,
java.lang.String pSep,
java.lang.String pAnd,
boolean pDescending)
Concatenate a String array into a long String. |
static java.lang.String |
blick(java.lang.String pName)
Read a block of sequential parameter lines into an array then return one element chosen at random. |
static java.lang.String[] |
blines(java.lang.String pName)
This method reads a block of sequentially-numbered lines from the Global Pizza and returns them as a String[] array. |
static java.lang.Double[] |
boxDouble(double[] pAry)
This method takes an int[] array and boxes it into Double[]. |
static java.lang.Integer[] |
boxInt(int[] pAry)
This method takes an int[] array and boxes it into Integer[]. |
static java.lang.String |
bread(java.lang.String pName,
java.lang.String pDelim)
This method reads a block of sequentially numbered lines from the Global Pizza and concatenates them as a single String using the supplied String as a delimiter. |
static boolean |
closeTo(double pLHS,
double pRHS)
Compare the difference of two doubles against the internal magnitude. |
static boolean |
closeTo(double pLHS,
double pRHS,
int pDelta)
This method checks to see if one double is 'close to' another. |
static Question |
createExpression(java.lang.String pVar,
java.lang.String pKnobs,
java.lang.String pTemplate)
This method creates an algebraic or other mathematical expression based on a variable, a Template, and a set of Knobs. |
static double[] |
dShuffle(double[] pAry)
The shuffle() a double[] array. |
static java.lang.String[] |
filter(java.lang.String[] pRaw,
java.lang.String pMatch)
This method checks each String in an array for a specified substring. |
static java.lang.String[] |
filter(java.lang.String pPrefix,
java.lang.String pMatch)
Shortcut method for filter(bLines(pPrefix), pMatch) . |
static java.lang.String |
flick(java.lang.String[] pRaw,
java.lang.String pMatch)
This method filters a String[] array per filter() and then randomly picks one of the resulting elements. |
static java.lang.String |
flick(java.lang.String pPrefix,
java.lang.String pMatch)
The flick(String[], String) method that operates on the Global Pizza. |
static MathToolsAccessory |
getAccessory(java.lang.String pName)
Create a MathToolsAccessory . |
static long |
getMTime()
This method echoes System.currentTimeMillis() should such be desirable. |
MathEngine_SCROB |
getSCROB()
Return a SCROB instance of this class. |
static long |
hitCount()
This method reflects CapCom.hitCount() . |
static int[] |
iShuffle(int[] pAry)
shuffle() an array of ints. |
static java.lang.String |
isoKnobs(java.lang.String pKnobs)
This method returns a String such that isoKnobs(pKnobs) == isoKnobs(isoKnobs(pKnobs)) . |
static Arithmetic |
newArithmetic()
Create and return an Arithmetic instance. |
static COFormatterFactory |
newCOFormatter()
Create a COFormatterFactory . |
static MathConsole |
newConsole()
Create and return a MathConsole anchored to CapCom. |
static GraphEngineFactory |
newGraphEngine()
Create a GraphEngineFactory . |
static MathDBC |
newMathDBC()
Create a MathDBC instance. |
static MathGenHTML |
newMathGenHTML()
Create a new MathGenHTML . |
static MathSet |
newMathSet()
Create a real-number MathSet . |
static MathStat |
newMathStat()
Create and return a MathStat instance. |
static MathXML |
newMathXML()
Create and return a MathXML() instance. |
static MComplex |
newMComplex(int pReal,
int pImag)
Create a MComplex number with the given components. |
static MEquation |
newMEquation()
Create and return a MEquation() instance. |
static MFraction |
newMFraction()
Create and return a MFraction. |
static MathGenLatex |
newMLatex()
Create a new MathGenLatex . |
static MMatrix |
newMMatrix()
Create and return a MMatrix. |
static MMatrixBuilder |
newMMBuilder()
Create and return a MMatrixBuilder. |
static MRadical |
newMRadical()
Create and return a MRadical() instance. |
static MTest |
newMTest()
Create and return a blank MTest. |
static MathTestFormatter |
newMTFormatter()
Create and return a MathTestFormatter . |
static MTXProcessor |
newMTXPro()
Create and return a MTXProcessor() instance. |
static Percent |
newPercent()
Create and return a Percent instance. |
static Polynomial |
newPolynomial(java.lang.String pData)
Create and return a Polynomial from a formatting String. |
static Question |
newQuestion()
Create and return a blank Question. |
static SimpleTagImpl |
newSimpleTag()
Create a new SimpleTagImpl . |
static MathDrawSVG |
newSVG()
Create a new MathDrawSVG . |
static int |
nzRandom(int pLow,
int pHigh)
Generate a nonzero random from a range. |
static java.lang.String |
parseRPN(java.lang.String pCalc)
Parse an RPN-formatted String and evaluate it numerically. |
static double |
random()
This is the principal (pseudo-) random number function. |
static int |
random(int pLow,
int pHigh)
Generate a random int from a range. |
static void |
reseed()
Reseed the random number generator from the system clock. |
static void |
reseed(long pSeed)
Reseed the random number generator with the given value. |
static int |
rPrime()
Pick a random prime number. |
static int |
rPrime(int pMax)
Pick a random prime number guaranteed to be less than the number given. |
static void |
setCloseTo(int pDelta)
This method sets the magnitude for the two-argument closeTo() . |
static int[] |
setKnobs(java.lang.String pKnobs)
A Knob is a random number selected from a range. |
static java.lang.Object[] |
shuffle(java.lang.Object[] pAry)
This method rearranges the elements in an Object[] array into random order. |
static java.lang.String[] |
spill(java.lang.String pData,
java.lang.String pSplitter,
int pLength,
java.lang.String pFill)
This method splits a String on the specified break-String and, if the resulting array is shorter than the length requested, pads the remaining elements with the specified fill String. |
static java.lang.String |
splick(java.lang.String pData)
Convenience method for splick() that splits on a single space character. |
static java.lang.String |
splick(java.lang.String pData,
java.lang.String pToken)
This method splits sData based on sToken and randomly picks one element from the resulting array. |
static int |
splickInt(java.lang.String pData)
This method splits a space-separated String of integers, picks one, and returns it as an int. |
Methods inherited from class java.lang.Object |
---|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
Field Detail |
---|
public static final int MAX_PRIME
rPrime()
methods: 1013.
public static final java.lang.String MEM_PREFIX
parseRPN()
.
Constructor Detail |
---|
public MathEngine()
Method Detail |
---|
public static double random()
This is the principal (pseudo-) random number function. It provides random numbers from zero (inclusive) to one (exclusive). It is probably not strong enough for serious cryptographic work but it should suffice for most math-test uses.
This method was changed in stable release 1.4 to make use of a java.util.Random
object. Very basic code was inserted to assure appropriate
randomness in the form of limiting runs of high or low values.
public static void adjustRandom(double pPower, double pRoot)
random()
, hence ALL random numbers generated here. If adjustment
is enabled the 'raw' random number generated is raised to the power (pPower/pRoot). That is: Adjusted = Math.pow(Raw, pExponent/pRoot)
. If
either argument is zero it is set to 1. If both are zero adjustment is disabled.
pPower
- The power used to adjust the 'raw' random generated. Minimum value is 1.pRoot
- The root applied to the raw random generated. Minimum value of 1.public static void reseed(long pSeed)
pSeed
- The new seed for the random generator.public static void reseed()
public static int random(int pLow, int pHigh)
pLow
- The low number in the range. Included in the possible return values.pHigh
- The high number in the range. Excluded from the possible return values.
public static int nzRandom(int pLow, int pHigh)
nzRandom(0,0)
will yield zero. Calling nzRandom(0, 1)
yields a value of one!
pLow
- The low int in the range (inclusive).pHigh
- The high end of the range (exclusive).
public static int rPrime()
public static int rPrime(int pMax)
pMax
- The upper limit for the prime number picked. If less than 10 it becomes 10.public static long hitCount()
CapCom.hitCount()
. It is useful for generating application-unique numbers.
public static int[] setKnobs(java.lang.String pKnobs)
A Knob is a random number selected from a range. What distinguishes it from any other random is that Knobs are generally picked more than one at a time. This method takes a space-separated String of numbers, breaks them into individual numbers, and interprets them pair-wise as low-end high-end values for a random function. One random value is generated for each pair of numbers in the parameter String. If the number of values in the String is odd, the last number is ignored.
By default this method generates nonzero randoms. To change this behavior place an equals sign in front of the low value in the range. E.g. '=-5 6' would choose a possibly-zero value between -5 and 5. NOTE: Since the Knob string is space-separated there must be NO SPACE between the equals sign and the number or negative sign!
If pKnobs is not formed properly (pairs of numbers, no non-numbers except the optional prefix) the return value is indeterminate. Any errors are reported at the Error level.
pKnobs
- A String of space-separated numbers.
public static java.lang.String isoKnobs(java.lang.String pKnobs)
isoKnobs(pKnobs) == isoKnobs(isoKnobs(pKnobs))
. That is, calling setKnobs on the resulting string yields
the same values each time.
pKnobs
- The original Knobs string.
setKnobs()
on will yield the same results.public static long getMTime()
System.currentTimeMillis()
should such be desirable.
public static boolean closeTo(double pLHS, double pRHS, int pDelta)
abs(pLHS - pRHS) < 5*Math.pow(10.0, -pDelta)
.
pLHS
- The first double to check.pRHS
- The second double to check.pDelta
- The order of magnitude to compare. Will be made positive if negative.
public static void setCloseTo(int pDelta)
closeTo()
. If pDelta is negative it is made positive when set. The default value is 1.
pDelta
- The magnitude for the two-double method.public static boolean closeTo(double pLHS, double pRHS)
closeTo()
.
public static java.lang.String splick(java.lang.String pData, java.lang.String pToken)
This method splits sData based on sToken and randomly picks one element from the resulting array. The name comes from 'split-pick'. If pData is null or empty it is returned unchanged. If pToken is null or empty, pData is split on spaces.
NOTE: This method utilizes the String.split()
method so regex collisions can occur! If such a thing happens the data String is returned whole
and the error is reported at Error level.
pData
- The String to be split.pToken
- The token around which pData is to be split.
public static java.lang.String splick(java.lang.String pData)
public static int splickInt(java.lang.String pData)
public static java.lang.String[] spill(java.lang.String pData, java.lang.String pSplitter, int pLength, java.lang.String pFill)
pData
- The String to be split.pSplitter
- The break-string to use for splitting pData. If null or blank, a space is used.pLength
- The guaranteed minimum length of the returned array.pFill
- The String used to pad the array if the splitting didn't give enough elements. If null, an empty String is used.
public static java.lang.Object[] shuffle(java.lang.Object[] pAry)
This method rearranges the elements in an Object[] array into random order. The array sent in is shuffled and returned. The shuffling method used is simple. The array is iterated over forward and backward five times. With each iteration there is a 55% chance that any element will be swapped with the adjascent element below it.
NOTE: This method does alter the array that is sent in. The element order is changed, the array is not copied!
pAry
- The array to shuffle.
public static int[] iShuffle(int[] pAry)
shuffle()
an array of ints.
public static double[] dShuffle(double[] pAry)
shuffle()
a double[] array.
public static java.lang.String[] blines(java.lang.String pName)
This method reads a block of sequentially-numbered lines from the Global Pizza and returns them as a String[] array. The lines must be of the form 'name.0= text', 'name.1= text', ... 'name.N= text', where 'name' is the common name for all of the lines. The numbering must start at zero and move up by one as the parsing stops with the first empty line. Once parsed, the lines are put into a String[] array and returned.
The name comes from 'block-lines.' If there are no such lines an empty array is returned.
pName
- The common name of the block of lines to read.
public static java.lang.String blick(java.lang.String pName)
pName
- The name of the block of lines to parse.
public static java.lang.String bread(java.lang.String pName, java.lang.String pDelim)
pName
- The name of the block of lines to parse.pDelim
- The concatenation delimiter String. If null or empty, a blank String ('') is used.
public static java.lang.String[] filter(java.lang.String[] pRaw, java.lang.String pMatch)
pRaw
- The String[] array from which to extract the desired Strings.pMatch
- The String to check against each element of pRaw.
public static java.lang.String[] filter(java.lang.String pPrefix, java.lang.String pMatch)
filter(bLines(pPrefix), pMatch)
. That is, it filters a block of parameters from the Global Pizza.
pPrefix
- The common block prefix per blines()
.pMatch
- The extraction substring.public static java.lang.String flick(java.lang.String[] pRaw, java.lang.String pMatch)
filter()
and then randomly picks one of the resulting elements. The method name is loosely derived
from 'filter-pick.'
pRaw
- The original array.pMatch
- The substring to match.
public static java.lang.String flick(java.lang.String pPrefix, java.lang.String pMatch)
flick(String[], String)
method that operates on the Global Pizza.
public static java.lang.String arCat(int[] pNums, boolean pAnd, boolean pWords)
pNums
- The int array to concatenate.pAnd
- true to set the last separator as 'and', false to leave it as a comma.pWords
- true to convert the numbers to words before concatenating.public static java.lang.String arCat(double[] pNums, boolean pAnd, boolean pWords)
arCat(int)
.
public static java.lang.String arCat(java.lang.String[] pAry, java.lang.String pSep, java.lang.String pAnd, boolean pDescending)
Concatenate a String array into a long String. The element separator and final element separator can be specified as can the direction of the concatenation. If the array sent in is null or empty a blank String is returned.
If 'pSep' is null it is replaced by a blank String (''). If 'pAnd' is null the value of 'pSep' is used. No other validity checking is done; if either of these Strings is defined that is what is used. If 'pDescending' is true the concatenation starts with the highest element in the array and moves down, otherwise it starts at zero and moves up.
pAry
- The String[] array to concatenate.pSep
- The separator to place between the elements. If null it defaults to a blank.pAnd
- The separator to place between the final two elements. If null it defaults to the value of 'pSep'.pDescending
- 'true' to start at the top value and move down, 'false' to start at zero and move up.public static java.lang.Integer[] boxInt(int[] pAry)
public static java.lang.Double[] boxDouble(double[] pAry)
public static java.lang.String parseRPN(java.lang.String pCalc)
Parse an RPN-formatted String and evaluate it numerically. The format for the string is RPN, so the calculation '4+7' would be entered '4 7 +'. The format uses spaces to separate the calculation tokens. This method implements a very simple stack-based calculator and the operations are evaluated as the String is parsed from left to right. Conceptually the calculator has two registers in addition to the Stack: R1 and R2. So the calculation above would be evaluated as follows:
In all cases R1 is the left-hand value and R2 is the right-hand value. That is, when an operation token is encountered, R2 is popped first followed by R1. The operation is evaluated and the result pushed back onto the stack. When all operations are finished, ONE (numerical!) value should remain in the Stack: this value is popped and returned as a String. NOTE: Any errors during the process will leave the Stack in an indeterminate state! If this happens, the return value CANNOT be guaranteed!
This method has two modes of operation: integer and floating-point. Integer mode is the default and should be used whenever possible. Floating-point mode, as implied by the name, uses floating-point numbers and is subject to all their foibles. Floating-point mode can be explicitly activated by making the first token '.' but it will be triggered by ANY decimal point ANYWHERE in the calculation!
The operations defined are:
Arithmetic.fix(R1, R2)
(floating-point mode only, fix 0 does NOT switch to integer mode).The following operations work on the last value pushed onto the stack. That number is popped (as R1), the function applied, and the result pushed. These
functions are from the java.lang.Math
package and they only operate in floating-point mode.
Memory Operations These operations make use of CapCom's Shelf for memory operations that can persist from one method call to another. There are three memory operations and one non-operation character defined:
EXAMPLE: The calculation '42 $life @s' stores the number '42' under the label 'Life'. Now '$Life @r' recalls '42' until it is deleted ('@d').
Although this method is useful by itself, its true power comes when combined with the Question.fillTemplate()
method. Complex calculations
can be pre-formatted with token elements, filled in at runtime and evaluated multiple times. This allows arbitrary computations to be created and altered
without recompiling a program! Particularly useful when combined with a scripting language.
pCalc
- A String containing RPN-formatted calculations.
public static Question createExpression(java.lang.String pVar, java.lang.String pKnobs, java.lang.String pTemplate)
This method creates an algebraic or other mathematical expression based on a variable, a Template, and a set of Knobs. The variable has a default value but the Template and Knobs must be specified. With all elements present, a Question is returned containing the Problem and Answer, properly formatted and correct.
The Template specifies the presentation and calculation elements of the expression. The basic format is 'Problem @@ calc_1:calc_2: ... :calc_n @@ Answer'. The calculation component may contain Knob tokens or literals: in operation the calculations are fed (as a single unit) into the Question.fillTemplate() method along with the values specified by the Knobs component. The calculation String is then split along the colons. The resulting array then supplies the fillTemplate() method again for both the Problem and Answer components.
IMPORTANT NOTE: For this method only the Knobs begin at <1>! That is to say, ordinarily the first element in the Knob array is element [0] but for this method ONLY the Knob number and the calculation number are the same! Knob 0 is always zero. In the Problem/Answer part token zero is the variable.
The exact sequence in which things occur is as follows:
Question.fillTemplate()
with the Knobs array (converted to String).parseRPN()
and evaluated.Question.fillTemplate()
.Question.fillTemplate()
.Example: The template is '<0> - <1> = <2> @@ <1> : <2> : <1> <2> + @@ <0> = <3>'. If the Knobs String is '5 15 20 60' and yields Knob[1]=7 and Knob[2]=41, the calculation String would be '7 : 41 : 7 41 +'. Suppose the variable given is 'Z'. The resulting String array is: token[] = {'Z', '7', '41', '48'}. The 48 comes from parseRPN('7 41 +'.) The filled-in Problem becomes 'Z - 7 = 41' and the Answer will be 'Z = 48'. These components are then placed into a Question and returned.
Any errors in the process result in an error Question being returned. While this method does not itself generate errors, calls to setKnobs(), parseRPN() or fillTemplate() might.
pVar
- The variable that replaces token 0. If null or blank a default variable ('x') is used.pKnobs
- The Knobs to be set for the result.pTemplate
- The template containing the parts of the expression.
public MathEngine_SCROB getSCROB()
public static Question newQuestion()
public static Arithmetic newArithmetic()
public static MathConsole newConsole()
public static Polynomial newPolynomial(java.lang.String pData)
public static Percent newPercent()
public static MFraction newMFraction()
public static MathStat newMathStat()
public static MMatrix newMMatrix()
public static MMatrixBuilder newMMBuilder()
public static MathXML newMathXML()
public static MEquation newMEquation()
public static MRadical newMRadical()
public static MComplex newMComplex(int pReal, int pImag)
public static MTXProcessor newMTXPro()
public static MTest newMTest()
public static MathTestFormatter newMTFormatter()
MathTestFormatter
.
public static MathToolsAccessory getAccessory(java.lang.String pName)
MathToolsAccessory
. If accessories are disabled the return value will be null.
public static COFormatterFactory newCOFormatter()
COFormatterFactory
.
public static MathDBC newMathDBC()
MathDBC
instance.
public static MathGenHTML newMathGenHTML()
MathGenHTML
.
public static MathDrawSVG newSVG()
MathDrawSVG
.
public static MathGenLatex newMLatex()
MathGenLatex
.
public static SimpleTagImpl newSimpleTag()
SimpleTagImpl
.
public static GraphEngineFactory newGraphEngine()
GraphEngineFactory
.
public static MathSet newMathSet()
MathSet
.
|
|||||||||
PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||
SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |