com.javathings.math package version 1.0

Author: Patrik Lundin,
patrik@javathings.com

This class library for Java contains two classes of interest, Derive.class and Eval.class .
Derive.class performs symbolic differentiation of a mathematical expression given as a string.
Eval.class evaluates a mathematical expression given as a string, with given values.

The com.javathings.math package is just $20 (USD)
You can purchase the package online here:
http://www.regsoft.net/purchase.php3?productid=31612

Index

Click on the underlined headers anywhere on the page
to return to this index.

Installation
Class Index
The Derive class
The Eval class
Example using the Derive class
Example using the Eval class
Exception notValidSyntaxException class
Exception cannotConvertException class
Supported operators and predefined constants
Juxtaposition
Variable naming
Compatibility
Sample Applets


Installation
The package is the "cjmath.jar" file, this file needs to be put into the CLASSPATH
so the java compiler can find it.
When distributing the package or if you for some other reason cannot use a jar file you
can extract it with the "jar" tool in Suns JDK:

  • jar -xf cjmath.jar
  • The com/javathings/demo folder can be removed when redistributing the package
    with your programs or applets.
     


    Class index

    package com.javathings.math :

    com.javathings.math.Eval extends java.lang.Object
    com.javathings.math.Derive extends java.lang.Object

    com.javathings.math.notValidSyntaxException extends java.lang.Exception
    com.javathings.math.cannotConvertException extends java.lang.Exception

    Constructor:
    Derive()
    Methods:

    public synchronized String[] diff( String expression , String variables ) throws notValidSyntaxException

    Method that performs symbolic derivation of a mathematical expression given as a string, 
    returns a string array containing the derivatives of the expression. 

    expression, the mathematical expression to differentiate as a string. 
    Ex. "cos(x+y+z)" , a list of supported operators can be found here
    variables, a list of variables separated with ";" Ex: "x;y;z" or "firstvariable;secondvariable" 
    Look at the variable naming convention for information on what variable names you can and cannot use. 
    The order of the string expressions in the returned array is the same as the order the variables appear 
    in variables. For example if expression is "cos(x+y+z)" and variables is "x;y;z" then d[ cos(x+y+z) ]/dx 
    will be in position 0, d[ cos(x+y+z) ]/d(y) will be in position 1 and d[ cos(x+y+z) ]/d(z) in position 2. 

    Any spaces in any of the arguments to diff will be ignored. 
    All alphabetic characters in the arguments will be converted to lowercase letters before processing.
     
     

    public synchronized String[] diff( String expression ) throws notValidSyntaxException

    Method that performs symbolic derivation of a mathematical expression given as a string, 
    returns a string array containing the derivatives of the expression. 

    expression, the mathematical expression to differentiate as a string. 
    Ex. "cos(x+yyy+zz)", a list of supported operators can be found here
    Differentiation will be made with regards to all variables found in the expression. 
    The order of differentiation is the same as the variables appear in the argument to diff(..), 
    counted from left to the right. Use getVariables() to get a list of all

    variables found after a call to diff(..) . 

    Any spaces in any of the arguments to diff will be ignored. 
    All characters in the arguments are converted to lowcase before processing.

    Both the diff methods throw a notValidSyntaxException
    if one of these errors occur when processing the first argument: 

    1. Invalid characters appear in the argument.

    2. Valid characters are: alphabetic characters a - z, numbers 0 - 9, brackets ( ) , dot . and one character operators + - * ^ / ..etc. 
      Using the (exception).getMessage() method will return: "Syntax error near -> [part of expression causing the exception]" 
    3. An operator is given without arguments or with too few arguments.

    4. Using the (exception).getMessage() method will return: "Wrong number of arguments to operator" 
    5. Non matching brackets appear. Using the (exception).getMessage() method will return: "Non matching brackets"
    The exception will also be thrown if these errors occur when processing the second argument: 
    1. Invalid characters appear. Only alphabetic characters a - z and numbers 0 - 9 are allowed in variable names.

    2. Using the (exception).getMessage() method will return: "Syntax error near -> [part of expression causing the exception]" 
    3. A variable name is a numeric value or contains an operator.

    4. Using the (exception).getMessage() method will return: "Not a valid variable [ the variable name causing the exception ]"


    public synchronized String getVariables()

    This method will return all variables found as a semi-colon delimited string after a call to any of the methods diff,
    or an empty string if no call to diff yet has been made.

    Example:

    Derive d = new Derive();
    d.diff( "cos( x+y+z )" );
    System.out.println( d.getVariables() );

    This will print "x;y;z" on standard out.
     

    Example of usage in a program:
    /*
    This example will derive an expression
    given at the command prompt.
    To run enter (with Suns java interpreter):
    >java Test 'expression' 'variables'
    For example:
    >java Test cos(x+y+z) x;y;z
    */
    
    import com.javathings.math.Derive;
    
    public class Test{
    
     public static void main(String arg[] ){
    
      // make an instance of the Derive class               
    
      Derive d = new Derive();
    
      int i = 0;
    
      try{
       // call the diff method with arguments               
       String ans[] = d.diff( arg[0] , arg[1] );
    
       // print answers
       while( ans[ i ] != null ){
        System.out.println(ans[ i ] );
        i++;
       }
      }catch(Exception e){
       System.out.println("ERROR: " + e.getMessage() );
      }     
     }
    }//end class
    
    

    Eval.class
    Constructor:
    Eval()
    Methods:

    public synchronized double eval( String expression , Hashtable htbl ) throws cannotConvertException

    Method for evaluating a mathematical expression given as a string, returns a double value. 

    expression, the mathematical expression to evaluate as a string. ex. "cos(x1+x2+x3)" 
    A list of supported operators and predefined constants can be found here
    All alphabetic letters will be converted to low case letters and all spaces will be ignored. 
    htbl, java.util.Hashtable with variables associated with values. 
    Both variables and values are given as strings, use only low case letters since the
    expression is converted to lowercase letters before processing. 
    Look at the variable naming convention for information on what variable names you can and cannot use. 
     
     

    public synchronized double eval( String expression , String values ) throws cannotConvertException

    Method for evaluating a mathematical expression given as a string, returns a double value. 

    expression, the mathematical expression to evaluate as a string. ex. "cos(x1+x2+x3)" 
    A list of supported operators and predefined constants can be found here
    values, string with variable=value pairs separated with semicolon ";" 
    Ex: x1=3.23;x2=2;x3=pi or x1=5-sin(x2);x2=pi^2;x3=1 
    Look at the variable naming convention for information on what variable names you can and cannot use. 
     
     

    public synchronized double eval( String expression ) throws cannotConvertException

    Method for evaluating a mathematical expression given as a string, returns a double value. 

    expression, the mathematical expression to evaluate as a string. ex. "cos(2*pi)" 
    A list of supported operators and predefined constants can be found here
    This method tries to evaluate it's argument, assuming that there's only operators and values in the argument 
    and no undefined variables. 

    The methods throws a cannotConvertException
    if one of these errors occur when processing the first argument: 

    1. Invalid characters appear in the argument.

    2. Valid characters are: alphabetic characters a - z, numbers 0 - 9, brackets ( ) , dot . and one character operators + - * ^ / ..etc. 
      Using the (exception).getMessage() method will return: "Syntax error near -> [part of expression causing the exception]" 
    3. An operator is given without arguments or with too few arguments.

    4. Using the (exception).getMessage() method will return: "Wrong number of arguments to operator" 
    5. Non matching brackets appear.

    6. Using the (exception).getMessage() method will return: "Non matching brackets"
    The exception will also be thrown if these errors occur when processing the second argument: 
    1. No value associated with a variable that appears in the first argument.

    2. Using the (exception).getMessage() method will return: "No value associated with [variable]" 
    3. Invalid characters appear in the argument.

    4. Valid characters are: alphabetic characters a - z, numbers 0 - 9, brackets ( ) , dot . and one character operators + - * ^ / ..etc. 
      Using the (exception).getMessage() method will return: "Syntax error near -> [part of expression causing the exception]" 
    5. A variable is associated with itself or an expression containing the same variable.

    6. Using the (exception).getMessage() method will return: "Neverending loop, [variable] is associated with [variable or expression]"

    Example of usage in a program:
    /*
    This example vill evaluate an expression 
    given at the command line.
    ( a command line calculator :-)
    To run enter: (with Suns java interpreter)
    > java calc 'expression'
    or 
    > java calc 'expression' 'values'
    For example: 
    > java calc sin(2*pi)-2*3+euler
    > = -8.718281828
    > java calc (x^2+y^2) x=2;y=2
    > = 8.0  
    */
    
    import com.javathings.math.Eval;
    
    public class calc{
    
     public static 
     void main(String arg[] )
     {
       // make an instance of the Eval class
       Eval e = new Eval();
    
       double ans = Double.NaN;
    
       try{
    
        // call the eval method with argument(s)
        if( arg.length == 1 ){
            // one argument, the expression can
            // only contain operators and values
            // no undefined variables
            ans = e.eval( arg[ 0 ] );
        }else{    
            // in case some variables=values are given
            // like: java calc sin(x)+2*y x=3;y=2
            ans = e.eval( arg[ 0 ] , arg[ 1 ] );
        }
        System.out.println( "= " + ans + "\n");
       }catch(Exception f){
        System.out.println("ERROR: " + f.getMessage() + "\n");
       }
     }
    } //end class
    
    

    notValidSyntaxException.class
    Constructor:
    notValidSyntaxException(String message)
    Description:
    Exception class used by Derive.class

    Call the getMessage method to retrive the message from an Exception that has been thrown. 
    Example: 

    Derive d = new Derive();
    String ans[];
    
    try{
    
      ans = d.diff("cos(x-y)+" , "x;y")
    
    }catch( notValidSyntaxException e ){
    
      System.out.println( e.getMessage() );
    
    }
    
    
    The above code segment will cause the message: "Wrong number of arguments to operator"
    to be printed on standard out.

    cannotConvertException.class
    Constructor:
    cannotConvertException(String message)
    Description:
    Exception class used by Eval.class

    Call the getMessage method to retrive the message from an Exception that has been thrown. 
    Example: 

    Eval e = new Eval();
    double ans = 0.0;
    
    try{
    
      ans = e.eval("cos(#x-y)" , "x=2;y=2.3")
    
    }catch( cannotConvertException f ){
    
      System.out.println( f.getMessage() );
    
    }
    
    
    The above code segment will cause the message: "Syntax error near -> #x-y)"
    to be printed on standard out.


    Supported operators

    All operator names are reserved, they cannot be used as a variable name
    or as a part of a variable name.

    The following operators and functions are supported by both diff(..) in Derive.class
    and eval(..) in Eval.class :
    + addition
    - subtraction
    * multiplication
    / division
    ^ raise to power of.. ( ex. x^2 )
    sqrt(..) squareroot
    sin(..) trigonometric functions
    cos(..) -"-
    tan(..) -"-
    cotan(..) -"-
    asin(..) arcus functions
    acos(..) -"-
    atan(..) -"-
    acotan(..) -"-
    sinh(..) hyperbolic functions
    cosh(..) -"-
    tanh(..) -"-
    exp(..) constant e raised to..
    ln(..) the natural logaritm

    Operators and functions supported only by eval(..) in Eval.class :
    abs(..) absolute value of....
    ceil(..) Returns the smallest (closest to negative infinity) 
    value that is not less than the argument and is equal to 
    a mathematical integer. 
    Example: ceil( 3.2 ) = 4.0 , ceil( 9.9 ) = 10.0
    floor(..) Returns the largest (closest to positive infinity) 
    value that is not greater than the argument and is 
    equal to a mathematical integer. 
    Example: floor( 3.2 ) = 3.0 , floor( 9.9 ) = 9.0
    fac(..) faculty of... 
    n*(n-1)*(n-2)*..*1
    sfac(..) semifaculty of.. 
    n*(n-2)*(n-4)*..*4*2 if n is even 
    n*(n-2)*(n-4)*..*3*1 if n is not even
    round(..) rounds the argument to the closest mathematical integer. 
    Example: round( 3.4 ) = 3.0, round( 4.99 ) = 5.0 etc...
    fpart(..) returns the decimalvalue of its argument 
    Example: fpart(2.345) = 0.345, fpart(4) = 0.0 etc..
    [base]log(..) any logaritm. 
    Example: 10log(10) = 1.0, exp(1)log(exp(1)) = 1.0
    % Modulo.
    Logical Operators Supported by eval(..) in Eval.class :
    == Equal, returns 1.0 if it's arguments are equal or 0.0 othervise.
    != Not Equal, returns 1.0 if it's arguments are not equal or 0.0 othervise.
    && And, returns 1.0 if both arguments evaluates to 1.0, or 0.0 othervise.
    || Or, returns 1.0 if any of it's arguments evaluates to 1.0, or 0.0 othervise.
    > Larger than, returns 1.0 if the value of the argument to the left is larger 
    than the value of the argument to the right, or 0.0 othervise.
    < Less than, returns 1.0 if the value of the argument to the left is less 
    than the value of the argument to the right, or 0.0 othervise.
    >= Larger than or equal to, returns 1.0 if the value of the argument to the left is larger 
    than or equal to the value of the argument to the right, or 0.0 othervise.
    <= Less than or equal to, returns 1.0 if the value of the argument to the left is less 
    than or equal to the value of the argument to the right, or 0.0 othervise.
    ! Not, returns 0.0 if it's argument evaluates to 1.0 and returns 1.0 if 
    it's argument evaluates to anything other than 1.0

    Operator Precedence:

    In order of evaluation, note that some operators is only
    supported by the Eval class.

    !
    cos sin tan sqrt exp.....etc
    ^
    * / %
    log
    + -
    > >= < <=
    == !=
    ||
    &&
     

    Constants and special values supported by eval(..) in Eval.class

    These are reserved names, they cannot be used as variables.
    pi Same value as java.lang.Math.PI, 3.14159.....
    euler Same value as java.lang.Math.E, 2.7182...
    infinity Same value as java.lang.Double.INFINITY
    -infinity Same value as java.lang.Double.NEGATIVE_INFINITY
    nan Same value as java.lang.Double.NaN
    true 1.0
    false 0.0


    Juxtaposition

    The package supports juxtaposition in the following type cases:

    variable jp one-arg-op , example: xcos(x)
    variable jp ( expr ) , example: x( 1 + x )
    const jp variable or one-arg-op , example: 2x , 2tan(x)
    const jp ( expr ) , example: 2(3+x)
    ( expr ) jp variable or one-arg-op , (2-x)x , (2-x)sin(x)
    ( expr ) jp  ( expr ) , example: (2-x)(x+1) , sin(x)(2-x)

    No other type cases is supported, for example juxtaposition
    between two variables is not supported since there is no way
    to determine where the first variable ends and the second starts.

    This means that "xx" is considered to be a variable, as well as "x2"
    or "variable2" but 2x is intepreted as juxtaposition.
     
     


    Variable naming

    Variable names can only consist of alphabetic letters a-z and numbers 0-9.
    For example: x, xx, aVariable, var1, var2, aVeryLongVariable .
    You can use any name that is not reserved by an operator or a constant,
    as a variable name.

    You cannot start a variable with a number, like for example 3x or 5var,
    this will be interpreted as juxtaposition ( ie. the same as 3*x and 5*var ).
     


    Compatibility

    The package conforms to the Java 1.02 API which ensures
    that it will run on most JVM's.
     
     


    Sample applets Using the package

    Calculator
    Derive Applet at University of Texas
    Newton Raphson Applet

    Also try the sample applets sent along in the "applet" folder:
    Calculator
    Graph