com.bestcode.mathparser
Interface IMathParser
- public interface IMathParser
IMathParser interface provides access to an implementation of the math parser
algorithm. MathParserFactory.create() can be used to get a pointer to this interface.
An instance of IMathParser is not thread safe. Do not share the same instance between
threads. Create a separate instance for each thread or do your own synchronization in
the way your application logic requires.
You can create a parser using MathParserFactory.create();
This will return you a IMathParser.
You can set the expression to parse using IMathParser.setExpression(String);
And you can get the result using double IMathParser.getValue();
|
Method Summary |
void |
createConstant(java.lang.String constName,
double constValue)
Creates a variable whose value is constant and cannot be changed. |
void |
createDefaultFuncs()
createDefaultFuncs method creates some predefined functions in the parser's list of functions. |
void |
createDefaultVars()
X, Y and PI variables are predefined and can be immediately used in the expression. |
void |
createFunc(java.lang.String newFuncName,
IFunction funcAddr)
createFunc method creates a new function that takes n number of parameters in
the parser's list of functions. |
void |
createVar(java.lang.String varName,
double varValue)
Same as setVariable(String, double); |
void |
deleteAllFuncs()
DeleteAllFuncs method deletes all variables from the list of available functions. |
void |
deleteAllVars()
DeleteAllVars method deletes all variables from the list of available variables. |
void |
deleteFunc(java.lang.String funcName)
deleteFunc method deletes an existing function from the list of available functions. |
void |
deleteVar(java.lang.String varName)
deleteVar method deletes an existing variable from the list of available variables. |
double |
evaluate()
Evaluates the expression and returns the result of it. |
void |
freeParseTree()
FreeParseTree can be explicitly called to free the resources taken by the
allocated Parse tree when an expression is parsed. |
java.lang.String |
getExpression()
Please see setExpression() method to read about Expression property. |
java.lang.String[] |
getFunctions()
Returns an array of functions declared for this parser. |
java.util.Locale |
getLocale()
Returns the locale of this parser instance. |
boolean |
getOptimizationOn()
Set OptimizationOn to let the bcParser component evaluate constant expressions
at parse time. |
double |
getValue()
Value property (getValue() method) is an intuitive way of retrieving the value of the input expression. |
double |
getVariable(java.lang.String varName)
Variable property is a way to set and get variable values. |
java.lang.String[] |
getVariables()
Returns the list of variables as an array of strings. |
double |
getX()
X property represents the X variable used in the mathematical expression which
was input to be evaluated. |
double |
getY()
Y property represents the Y variable used in the mathematical expression which
was input to be evaluated. |
boolean |
isFunction(java.lang.String funcName)
Returns true if a function with the name 'funcName' is present in the current functions list. |
boolean |
isFuncUsed(java.lang.String funcName)
Returns true if a function with the name 'funcName' is used in the current expression. |
boolean |
isVariable(java.lang.String varName)
Returns true if a variable with the name 'varName' is present in the current variables list. |
boolean |
isVariableUsed(java.lang.String varName)
Returns true if a variable with the name 'varName' is used in the current expression. |
void |
optimize()
Optimizes the parse tree by finding branches that evaluate to a constant and
replacing them with a leaf representing the constant. |
void |
parse()
Parses the expression and forms a parse tree. |
void |
setExpression(java.lang.String newVal)
Expression property represents the mathematical expression which is input to be evaluated by the user. |
void |
setLocale(java.util.Locale l)
Sets the locale for the parser to use while constructing messages. |
void |
setOptimizationOn(boolean newVal)
Set OptimizationOn to let the bcParser component evaluate constant expressions
at parse time. |
void |
setVariable(java.lang.String varName,
double newVal)
Variable property is a way to set and get variable values. |
void |
setX(double newVal)
X property represents the X variable used in the mathematical expression which
was input to be evaluated. |
void |
setY(double newVal)
Y property represents the Y variable used in the mathematical expression which
was input to be evaluated. |
getExpression
public java.lang.String getExpression()
- Please see setExpression() method to read about Expression property.
setExpression
public void setExpression(java.lang.String newVal)
- Expression property represents the mathematical expression which is input to be evaluated by the user.
The expression can contain variables such as X, Y, T, HEIGHT, WEIGHT and so on.
Expression can also contain functions that take one parameter, or two parameters.
Variable and Function names are not case sensitive.
When Expression is assigned a value, it becomes 'dirty' and further attempt to
evaluate its value will require it to be parsed. But once it is parsed,
and a parse tree representing the expression is formed, it won't be parsed again,
until it is assignd a new string. Instead, the parse tree will be used to retrieve
current results as the values of variables change.
X, Y and PI variables are predefined and can be immediately used in the expression.
CreateVar method can be used to add user variables.
Predefined functions that take one parameter are:
SQR: Square function which can be used as SQR(X)
SIN: Sinus function which can be used as SIN(X), X is a real-type expression.
Sin returns the sine of the angle X in radians.
COS: Cosinus function which can be used as COS(X), X is a real-type expression.
COS returns the cosine of the angle X in radians.
ATAN: ArcTangent function which can be used as ATAN(X)
SINH: Sinus Hyperbolic function which can be used as SINH(X)
COSH: Cosinus Hyperbolic function which can be used as COSH(X)
COTAN: which can be used as COTAN(X)
TAN: which can be used as TAN(X)
EXP: which can be used as EXP(X)
LN: natural log, which can be used as LN(X)
LOG: 10 based log, which can be used as LOG(X)
SQRT: which can be used as SQRT(X)
ABS: absolute value, which can be used as ABS(X)
SIGN: SIGN(X) returns -1 if X<0; +1 if X>0, 0 if X=0; it can be used as SQR(X)
TRUNC: Discards the fractional part of a number. e.g. TRUNC(-3.2) is -3, TRUNC(3.2) is 3.
CEIL: CEIL(-3.2) = 3, CEIL(3.2) = 4
FLOOR: FLOOR(-3.2) = -4, FLOOR(3.2) = 3
RANDOM:
RND(X) generates a random INTEGER number such that 0 <= Result < int(X).
If X is negative, then result is int(X) < Result <= 0.
RANDOM(X) generates a random floating point number such that 0 <= Result < X.
If X is negative, then result is X < Result <= 0.
Predefined functions that take two parameters are:
INTPOW: The INTPOW function raises Base to an integral power. INTPOW(2, 3) = 8.
Note that result of INTPOW(2, 3.4) = 8 as well.
POW: The Power function raises Base to any power. For fractional exponents or
exponents greater than MaxInt, Base must be greater than 0.
LOGN: The LogN function returns the log base N of X. Example: LOGN(10, 100) = 2
MIN: MIN(2, 3) is 2.
MAX: MAX(2, 3) is 3.
MOD: MOD(x,y) function implements the Java % (modulus) operator.
Predefined functions that take three parameters are:
IF: The IF(b, case1, case2) function provides branching capability.
If b is not 0, then it returns case1, else it returns case2.
Behavior is similar to Java's: return b ? case1 : case2;
If b==0 then case1 will not be evaluated, and vice versa.
Example: IF(HEIGHT, 3/HEIGHT, 3) will make sure 3/HEIGHT does not cause division by zero.
User functions can be added using createFunc method.
Functions and Variables can be deleted using DeleteVar, DeleteFunc,
DeleteAllVars, DeleteAllFuncs methods.
Supported operators are +,-,*,/,^,% (integer division), =(equals),&(and),|(or),!(not), <>(not equals), <=(less than or equals), >=(greater than or equals)
getValue
public double getValue()
throws java.lang.Exception
- Value property (getValue() method) is an intuitive way of retrieving the value of the input expression.
Value property is a read only property which is in fact just an alias for the Evaluate method.
java.lang.Exception
getVariable
public double getVariable(java.lang.String varName)
throws java.lang.Exception
- Variable property is a way to set and get variable values.
Throws Exception if the variable does not exist.
Variable name is not case sensitive.
java.lang.Exception
setVariable
public void setVariable(java.lang.String varName,
double newVal)
throws java.lang.Exception
- Variable property is a way to set and get variable values.
setVariable function creates the variable if the variable does not exist.
Variable name is not case sensitive. Throws exception if the variable needs
to be created and the name is not a valid variable name. createVar is just an
alias for this method.
java.lang.Exception
getX
public double getX()
throws java.lang.Exception
- X property represents the X variable used in the mathematical expression which
was input to be evaluated. You can set the X variable to a numeric value and
call the Parse method (or Value property) to retrieve the new result of the expression.
X variable is created by default for the convenience of the user.
Additional variables can be added by using the CreateVar method.
Variable names are case insensitive.
java.lang.Exception
setX
public void setX(double newVal)
- X property represents the X variable used in the mathematical expression which
was input to be evaluated. You can set the X variable to a numeric value and
call the Parse method (or Value property) to retrieve the new result of the expression.
X variable is created by default for the convenience of the user.
Additional variables can be added by using the CreateVar method.
Variable names are case insensitive.
getY
public double getY()
throws java.lang.Exception
- Y property represents the Y variable used in the mathematical expression which
was input to be evaluated. You can set the Y variable to a numeric value and
call the Parse method (or Value property) to retrieve the new result of the expression.
Y variable is created by default for the convenience of the user.
Additional variables can be added by using the CreateVar method.
Variable names are case insensitive.
java.lang.Exception
setY
public void setY(double newVal)
- Y property represents the Y variable used in the mathematical expression which
was input to be evaluated. You can set the Y variable to a numeric value and
call the Parse method (or Value property) to retrieve the new result of the expression.
Y variable is created by default for the convenience of the user.
Additional variables can be added by using the CreateVar method.
Variable names are case insensitive.
getOptimizationOn
public boolean getOptimizationOn()
- Set OptimizationOn to let the bcParser component evaluate constant expressions
at parse time. The optimized parse tree will enhance subsequant evaluation
operations, though initial parsing will be slower.
Optimization is good if you are going to parse once and evaluate the same
expression many many times with different variable values.
setOptimizationOn
public void setOptimizationOn(boolean newVal)
- Set OptimizationOn to let the bcParser component evaluate constant expressions
at parse time. The optimized parse tree will enhance subsequant evaluation
operations, though initial parsing will be slower.
Optimization is good if you are going to parse once and evaluate the same
expression many many times with different variable values.
evaluate
public double evaluate()
throws java.lang.Exception
- Evaluates the expression and returns the result of it. If it cannot be parsed or
evaluated then this method throws Exception.
Calling this method is identical to calling getValue()
java.lang.Exception
parse
public void parse()
throws java.lang.Exception
- Parses the expression and forms a parse tree. Throws Exception if it cannot parse.
Upon successful completion of parsing, it will set the Dirty flag to false, so that
unless the expression is changed or variables and functions added or removed,
expression does not need to be re-parsed. Users may want to call the parse method
directly to check the validity of an input expression using a try-except block.
If OptimizationOn property is true, Parse method will optimize the parse tree by
evaluating constant branches of the parse tree at that moment, so that Evaluate
function will run faster.
java.lang.Exception
createVar
public void createVar(java.lang.String varName,
double varValue)
throws java.lang.Exception
- Same as setVariable(String, double);
java.lang.Exception
createConstant
public void createConstant(java.lang.String constName,
double constValue)
throws java.lang.Exception
- Creates a variable whose value is constant and cannot be changed.
Using constants where possible enables the optimizer recognize
constant branches and simplify them into single constant nodes to improve
evaluation performance.
- Parameters:
constName - constValue -
- Throws:
java.lang.Exception
createFunc
public void createFunc(java.lang.String newFuncName,
IFunction funcAddr)
throws java.lang.Exception
- createFunc method creates a new function that takes n number of parameters in
the parser's list of functions. If the function name already exists, then
createFunc throws Exception.
Function name is not case sensitive.
The second parameter is a reference to an implementation of the handler interface:
interface IFunction {
     public double run(IParameter[] parameters);
     public int getNumberOfParams();
}
While evaluation of the expression, when the registered function name is
encountered, the user supplied IFunction.run(IParameter[]) will be called.
This event handler ( IFunction.run(IParameter[]) )
will need to return a result (representing the value of the function)
based on the parameters passed as an array of double values.
The number of parameters that this newFuncName function will take is determined by
the IFunction funcAddr parameter's IFunction.getNumberOfParams() method.
java.lang.Exception
createDefaultFuncs
public void createDefaultFuncs()
throws java.lang.Exception
- createDefaultFuncs method creates some predefined functions in the parser's list of functions.
Predefined functions that take one parameter are:
SQR: Square function which can be used as SQR(X)
SIN: Sinus function which can be used as SIN(X), X is a real-type expression. Sin returns the sine of the angle X in radians.
COS: Cosinus function which can be used as COS(X), X is a real-type expression. COS returns the cosine of the angle X in radians.
ATAN: ArcTangent function which can be used as ATAN(X)
SINH: Sinus Hyperbolic function which can be used as SINH(X)
COSH: Cosinus Hyperbolic function which can be used as COSH(X)
COTAN: which can be used as COTAN(X)
TAN: which can be used as TAN(X)
EXP: which can be used as EXP(X)
LN: natural log, which can be used as LN(X)
LOG: 10 based log, which can be used as LOG(X)
SQRT: which can be used as SQRT(X)
ABS: absolute value, which can be used as ABS(X)
SIGN: SIGN(X) returns -1 if X<0; +1 if X>0, 0 if X=0; it can be used as SQR(X)
TRUNC: Discards the fractional part of a number. e.g. TRUNC(-3.2) is -3, TRUNC(3.2) is 3.
CEIL: CEIL(-3.2) = 3, CEIL(3.2) = 4
FLOOR: FLOOR(-3.2) = -4, FLOOR(3.2) = 3
RANDOM:
RND(X) generates a random INTEGER number such that 0 <= Result < int(X).
RANDOM(X) generates a random floating point number such that 0 <= Result < X.
Predefined functions that take two parameters are:
INTPOW: The INTPOW function raises Base to an integral power. INTPOW(2, 3) = 8. Note that result of INTPOW(2, 3.4) = 8 as well.
POW: The Power function raises Base to any power. For fractional exponents or exponents greater than MaxInt, Base must be greater than 0.
LOGN: The LogN function returns the log base N of X. Example: LOGN(10, 100) = 2
MIN: MIN(2, 3) is 2.
MAX: MAX(2, 3) is 3.
MOD: MOD(x,y) function implements the Java % (modulus) operator.
Predefined functions that take three parameters are:
IF: The IF(b, case1, case2) function provides branching capability.
If b is not 0, then it returns case1, else it returns case2.
Behavior is similar to Java's: return b ? case1 : case2;
If b==0 then case1 will not be evaluated, and vice versa.
Example: IF(HEIGHT, 3/HEIGHT, 3) will make sure 3/HEIGHT does not cause division by zero.
java.lang.Exception
createDefaultVars
public void createDefaultVars()
- X, Y and PI variables are predefined and can be immediately used in the expression.
Initial values of X and Y are 0. PI is 3.14159265358979
deleteVar
public void deleteVar(java.lang.String varName)
- deleteVar method deletes an existing variable from the list of available variables.
If the variable does not exist, then deleteVar does nothing.
When a variable is deleted Dirty flag is set to true so that next time
the Evaluate function is called the expression will be reparsed.
Variable name is not case sensitive.
deleteFunc
public void deleteFunc(java.lang.String funcName)
- deleteFunc method deletes an existing function from the list of available functions.
If the function does not exist, deleteFunc does nothing.
When a function is deleted Dirty flag is set to true so that next time the
Evaluate function is called the expression will be reparsed.
Function name is not case sensitive.
deleteAllVars
public void deleteAllVars()
- DeleteAllVars method deletes all variables from the list of available variables.
This action may be useful when number of unused variables is too high that
causes performance to degrade.
When a variable is deleted Dirty flag is set to true so that next time the
Evaluate function is called the expression will be reparsed.
deleteAllFuncs
public void deleteAllFuncs()
- DeleteAllFuncs method deletes all variables from the list of available functions.
This action may be useful when number of unused functions is too high that
causes performance to degrade.
When a function is deleted Dirty flag is set to true so that next time the
Evaluate function is called the expression will be reparsed.
getVariables
public java.lang.String[] getVariables()
- Returns the list of variables as an array of strings.
Each element of the array is guaranteed not to be null.
getFunctions
public java.lang.String[] getFunctions()
- Returns an array of functions declared for this parser.
Elements of the array are guaranteed not to be null.
freeParseTree
public void freeParseTree()
- FreeParseTree can be explicitly called to free the resources taken by the
allocated Parse tree when an expression is parsed. FreeParseTree sets the Dirty
flag to true so that next time the Evaluate function is called, expression will
be parsed forming a new, valid parse tree to be evaluated.
isVariableUsed
public boolean isVariableUsed(java.lang.String varName)
throws java.lang.Exception
- Returns true if a variable with the name 'varName' is used in the current expression.
Variable name is not case sensitive. Throws exception if expression is not parsed
and cannot be parsed.
java.lang.Exception
isFuncUsed
public boolean isFuncUsed(java.lang.String funcName)
throws java.lang.Exception
- Returns true if a function with the name 'funcName' is used in the current expression.
Function name is not case sensitive. Throws exception if expression is not parsed and cannot be parsed.
java.lang.Exception
isVariable
public boolean isVariable(java.lang.String varName)
- Returns true if a variable with the name 'varName' is present in the current variables list.
isFunction
public boolean isFunction(java.lang.String funcName)
- Returns true if a function with the name 'funcName' is present in the current functions list.
optimize
public void optimize()
- Optimizes the parse tree by finding branches that evaluate to a constant and
replacing them with a leaf representing the constant.
Until the expression is changed and reparsed, further evaluation requests will be
quicker.
If the same expression will not be evaluated repeatedly with varying
values of parameters used in it, then optimization will not bring any gain,
but will slow performance.
If OptimizationOn property is set to true, this method is called automatically when an
evaluation is requested by calling Evaluate method or getValue() method.
setLocale
public void setLocale(java.util.Locale l)
- Sets the locale for the parser to use while constructing messages.
Parser holds a static pool of translated messages mapped for each locale.
When this method is called, it first checks to see if the resource bundle
is already loaded in this pool. If it is loaded, it re-uses that pool.
If it was not loaded before, it loads it, adds it to the pool and
sets the specific bundle for this instance of the parser to use.
This mechanism allows the parser instances in the same VM efficiently
use different locales independent of each other. For example, if you
instantiate 100 parsers to use US English locale and then another 200
to use Chineese, then the parser will load the two resource bundles
for once each and related instances will share the same ones.
When you set a locale, let's say "de_DE", you need to have a matching
property file to be loaded by the parser,
"com/bestcode/mathparser/mathparser_de_DE.properties".
If such file is not found, the default version
("com/bestcode/mathparser/mathparser.properties"), which contains English
messages will be loaded. The file IO is done once for each locale,
not for each instance of the parser.
Messages may contain parameter placeholders. For example:
"Variable {0} does not exist". You need to have your own messages translated
accordingly.
getLocale
public java.util.Locale getLocale()
- Returns the locale of this parser instance.