Share how you use mXparser

If you use mXparser sharing this information is more than welcome 🙂 Please post a comment to that page describing in a few word your use case.

Thanks,

Mariusz Gromada

*** If you found the software useful donation is something you might consider 🙂 ***

If you found the software useful donation is something you might consider :-)

78 thoughts on “Share how you use mXparser

  1. This parser is great, I am using it to my thesis project where solving user input formulas is the goal.

    Thanks a lot!

    Leroy

  2. Mariusz Gromada,

    This parser is awesome! I am using it to finish a capstone class project. The user of my program can enter an equation in many formats. This parser enables me to ignore the headache of parsing the strings myself. It's almost like running the user input as code.

    Thank you!

      1. Hope you may be able to help with this small issue I have had. I am using an array of arguments. When I want to get the value of one argument and return the double I am using getArgumentValue. However, this is returning only an estimate of the argument value.

        For example, argument1 has value 748.429.
        getArgumentValue returns 750.0

        Is there an easier way to get the value to return accurately as a double?

        1. Thank you for your message. Of course I will be happy to help 🙂 I will contact you directly via email.

          Best regards

        2. Issue reported by TW was a consequence of constructor definition. Generally speaking constructor Argument(String argumentName, String argumentExpressionString, PrimitiveElement... elements) should be used for "dependent" argument creation, where argument value depends on the expression provided in argumentExpressionString and optional other arguments, constants, functions given in the variadic PrimitiveElement list. Calling getArgumentValue() method on dependent argument will always call calculate() on the hidden expression, thus if expression is "constant" (no arguments) the value will be always the same. To avoid this situation always carefully choose the constructors, and if still not sure, check argument type calling getArgumentType().

          Thank you for great question and the feedback! 🙂

          Kind regards

          1. Hello!
            I need to show what he thought of the derivative function.
            It's so f (x) = x ^ 3 f (x) '= 3 * x ^ 2. How to do it? Could you help me? Der function (sin (x), x) calculates only. And I need to show the derivative.

    1. Thank you very much for the feedback! I am aware of double disadvantages, but still decided to stick with double as my parser is implemented also in C#/.NET where BigDecimal is not available (or it was not present before). Additionally parser was written from the mathematician point of view. I understand that in case of money calculation it might be an issue. In the next release there will we delivered nice "round" function with "precision" parameter.

      Best regards,
      Mariusz

    2. 3.0.0 will bring intelligent automatics ulp rounding, this will minimize issues similar to the 0.1 + 0.1 + 0.1 = 0.30000000000000004

      Nest regards

  3. Hello Mr Gromada, thank you for the useful product you are developing. I wanted to ask whether the parser will support complex numbers, vectors or cubic/quadratic equation solving in the future?
    Thank you very much in advance!

    1. Dear Theme,

      Thank you for your feedback - it is very important to me!

      Regarding complex number - I am thinking about that - it would be great as mXparser supports user defined recursion. Other things like vectors ... we will see.

      Kind regards

  4. I am very thankful for your effort, but:
    1. when I calculate sin(pi), it gave a very small number (order to 10^-16) but not zero
    2. when I install 3.0.0 to my package in xamarin via NuGet, the following error came out:
    Could not install package 'MathParser.org-mXparser 3.0.0'. You are trying to install this package into a project that targets 'portable-net45+win+wp80+MonoTouch10+MonoAndroid10+xamarinmac20+xamarinios10', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

    I will be glad if you can fix that

    Thanks.

    1. Dear Nat Chen,

      Thanks a lot for your feedback!

      Referring to the point 1 - I am guessing this is the double precision issue as pi is represented as double number. But yes i can extend sine function definition to check whether argument is equal to numerically defined n*pi then set to 0.

      In case of point 2 - nuget package was prepared targeting .NET framework 4.0 client profile. I assume I should prepare some other version of nuget package?

      Best regards

        1. Dear Nat Chen,

          I need few days to manage that. I know what needs to be done (Portable Class Library for .NET). Initially I tested mXparser for PCL - after few minor changes it worked, but requires some small API changes.

          Best regards

          1. I do think that is a problem of your program setting in NuGet that you say you support Android but not iOS. However, this problem was not happening in 2.4.0 version. Please check. Thanks.

          2. Currently Android is supported only in JAVA library. I am working on the PCL version for .NET - according to Visual Studio PCL will work with Xamarin.

            Best regards

      1. AFAIK, in .NET it should not be so complicated since System.Numerics supports Complex numbers after NET 4.0. If you plan to build the Complex structure from scratch, it will take a lot of time.

        Best Regards!

        1. mXparser provides API for JAVA and .NET - I plan to keep this, so thinking about development I need to consider this.

          Best regards

  5. I am looking into using mxparser into evaluating expression (rules) that match binary expressions in data with is in a Map. So functionally something like map.get('key')[0].equals('something'). Would this be possible with mxparser?

    1. Dear Michel,

      Thank you for your feedback. Can you please provide more details on this specific use case?

      Kind regards

      1. I have Map<String,List> and expressions on that map. The values (typically a list with length 1, can be a string, integer, or even date. What I would like to be happening is defining an expression alike 'property[a] = property[b] && properyty[start-date] >= date-calc[now - day[1]].

        For now I'm taking the approach that I'm parsing the expression above and end up with a math expression that mxparser can handle.

  6. Greetings,
    I am developing an android math application. It will be free. I will, however, put in adverts on the app. I wont alter the code in any way. I only want to use the .jar to parse mathematical expressions. Should I issue out the source code? What do I need to do not to infringe on the license. I looked everywhere for your email and I could not find it.

    1. Hi,
      You can use mXparser without limitations (binary, source, changing source - everything is allowed). You do not need to publish your source code. The only requirement according to the license is to retain / redistribute copyright notice - please follow: http://mathparser.org/mxparser-license/

      Best rgards

  7. I'm using it for a calculator and it's great. I would like to indicate some bugs
    Expression relating factorial " ! " cause the application to hang and stop working.
    For example
    A. 5!^2 (where power symbol comes immediately after factorial )
    B. 5!-3 and 5!+3 or similar expressions
    C. 10/5-(5!) and 10/5+(5!) or similar expressions (though 10/5+5! works fine, but when I put brackets around factorial it stops responding )

  8. I made test using Apache POI formula evaluater and mxparser and testing the same expression, the result was that, mxparser was 4 times slower than Apache POI...

    1. Thank you for your opinion. I do not claim mXparser is the fastest. Please check some options that can speed up calculation process:

      mXparser.disableUlpRounding();
      mXparser.setExactComparison();

      Best regards

  9. Hey Mariusz,

    I had a quick query.
    We are planning to use your library in one of our application and while doing the POC, we came across a scenario wherein we are required to validate if the expression is a valid expression (For eg : (2=3) | (2<3) should show as correct but (2=3) | (2<3 should throw an error since the closing bracket is missing. Is there any support for such validation in the library? Also, we need to validate the expression before it is actually executed.

    Thanks in advance!

    -Melwin

    1. Hi Melwin,

      This is already supported. Please refer to checkSyntax() and getErrorMessage() in Expression class. Please find below example:

      Expression e = new Expression("(2=3) | (2<3)");
      System.out.println("-------------- Case 1 --------------");
      System.out.println("Syntax : " + e.checkSyntax());
      System.out.println("Message : " + e.getErrorMessage());
      System.out.println("-------------- Case 2 --------------");
      e.setExpressionString("(2=3) | (2<3");
      System.out.println("Syntax : " + e.checkSyntax());
      System.out.println("Message : " + e.getErrorMessage());

      -------------- Case 1 --------------
      Syntax : true
      Message : [(2=3) | (2<3)] checking ...
      [(2=3) | (2<3)] no errors.

      -------------- Case 2 --------------
      Syntax : false
      Message : [(2=3) | (2<3] checking ...
      [(2=3) | (2<3] lexical error

      Encountered "" at line 1, column 12.
      Was expecting one of:
      ")" ...
      "+" ...
      "-" ...
      "*" ...
      "/" ...
      "^" ...
      "%" ...
      "!" ...
      ...
      ...
      "< " ... "<=" ... ">" ...
      ">=" ...
      ...
      ...
      ...
      ...
      ...
      ...
      ...
      ...
      ...
      ...

      [(2=3) | (2<3] errors were found.

      Best regards.

      1. Hey Mariusz,

        Thanks a lot for the reply!

        I have one addition problem as well.

        We have an expression as - IF(arg1="ABC",1,0)

        wherein we need to compare the argument to a String, is this supported?

        I tried writing the expression as ,

        Expression exp = new Expression("if(arg1='ABC',1,0)",arg1);

        (But it didn't work)

        I did try other methods as well, but no success 🙁

        So , is such a comparison supported?

        Thanks again in advance !

        Regards,
        Melwin

          1. Oh! I see. Nonetheless, it's a really good parser and also thank you Mariusz for your super quick responses!

            - Melwin

  10. Hi Mariusz,

    We were using your library to build an expression.
    And we used the checkSyntax() method to validate our expression.

    - We accept the expression from the user Eg : ((_d1+(_d^_g)))
    - Also, we extract the variable name from the expression using getCopyOfInitialTokens() and identify the variables by matching tokens having underscore in the token name
    - Then we assign value to variables and then create an Expression as ,
    Expression ex = new Expression(formula,argumentList.toArray(new Argument[argumentList.size()] ));
    where argumentList is the list of arguments
    - Then we check the syntax of the expression

    So, the issue here is,
    - if the user places an extra parenthesis at the beginning, the getCopyOfInitialTokens() works fine but checkSyntax() gives false
    - however, if the user places an extra parenthesis at the end, the getCopyOfInitialTokens() throws an exception (java.util.EmptyStackException)
    - Unfortunately it is a catch 22 situation, because to check the syntax we need the arguments and to get the arguments we need to use getCopyOfInitialTokens().

    Any help?

    Thanks.

    - Akagra

      1. It seems this is related to stack issue. Lexer analysis has to be ok for getCopyOfInitialTokens - i will add checkLexerSytnatx() method.

  11. Hi Mariuz,
    Excellent work, thanks..

    I need to obtain values from a nested sum, is it possible to call an external function (web service) to get this values?

    Constant a = new Constant("w = 3");
    Constant b = new Constant("z = 2");
    Function g = new Function("NR(x,s) = ???"); // matrix values or web service call
    Function f = new Function("NP(x,s) = ???");
    Function i = new Function("f(x,s) = NR(x,s) + NP(x,s)", g, f);
    Function h = new Function("func(s) = (1/z) * sum(x, 1, z, f(x,s))", b, i);
    String expStr = "(1/w) * sum(s, 1, w, func(s))";

    or maybe call a web service and define an array or matrix of arguments...

    Any help ??

  12. Hi Mariuz
    I am loving this so far but, I need a bit of help with something.
    I am trying to make a calculator for Android but I can't figure this out.

    I have a String with the literal expresion to be solved. I'm using the mxparser to solve it but, how can you display the result on the textView?

    1. Hi Darío,

      Assuming you have string s with expression, i.e.:

      String s = "1+2";
      Expression e = new Expression(s);
      String result = Double.toString(e.calculate());

      You can then send result to the textView.

      Best regards

      1. Hi.
        Thanks for attending my Comment.
        I'm getting some errors while trying to run the app.
        The report says:

        -Error:Error converting bytecode to dex:
        Cause: java.lang.RuntimeException: Exception parsing classes

        -Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
        > com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_71\bin\java.exe'' finished with non-zero exit value 1.

        I wrote the method as you said. In case it might help, I'll write it too.
        The operation is in the String named result

        public void solve (View view){
        Expression solution = new Expression(result);
        String finalAnswer = Double.toString(solution.calculate());
        display(finalAnswer);
        }

        Thanks for your time

  13. Hi Mariusz,

    Thanks for sharing this great library.
    I'm thinking of adopting this library for custom added function parsing tool.
    By the way after I reviewed the API document I couldn't find any aggregate functions which support arguments as a list or array format.
    I'd like to parse the following equation

    eq = abs(max(y)-min(y))

    At this time y is type of array
    Am I missed somthing?

    Thnanks in advance.

        1. If you use JAVA, try this:

          String expression = "max(" + StringUtils.join(array,",") + ")";
          Expression e = new Expression(expression);

          I had the same problem and this works for me.

          Best regards.

  14. Hi Mariusz,

    I have a hash table Map<Object, List> and I need to aggregate each array of Double.

    As a sample, I created a map with one key and an array with 365 values.

    The time to find the maximun among these 365 values is 18 secs.

    Here the code:

    final_map = map_as_list.entrySet()
    .stream()
    .collect(
    Collectors.toMap(entry -> entry.getKey(),
    entry -> {
    List list = entry.getValue().stream()
    .collect(Collectors.toList());
    Double[] array = list.toArray(new Double[list.size()]);
    String expression = "max"+"(" + StringUtils.join(array,",") + ")";
    Expression e = new Expression(expression);
    double value = e.calculate();
    value = Math.round(value * 1000); value = value / 1000;
    return value;
    }));

    How could I increase the performance? Is there a better way to use this library over a hash table?

    Thanks.

    Besta Regards,
    Fabrizio

  15. VB.net, VS 2012, stepping through the "Hello World!" demo(and my own project) I get the following error "Cannot find Expression.cs". When I let the program run normally, it does function but extremely slow. What is going on?

  16. Hi Mariusz. I have a question. How to shown in the console derivative of the function. Example:
    Input: x ^ 2-4 * sin (x)
    Output in the console: 2 * x-4 * cos (x)

    Here is the code
      public static double derivative (String f, double znach) {
             String znak = Double.toString (znach);
             Argument x = new Argument ( "x =" + znak);
             Expression e = new Expression ( "der (" + f + ", x)", x);
             mXparser.consolePrintln ( "Res:" + e.getExpressionString () + "=" + e.calculate ());
             return e.calculate ();
         }
    Thank's

  17. Hi, Mariusz

    Thanks for your great parser! I have used it in Jdeveloper IDE - all work fine. Today I have tried the same code in Eclipse IDE.
    import org.mariuszgromada.math.mxparser.Expression;
    public class CalculatorImpl {
    Expression e = new Expression("2+2");

    And eclipse hightlight constructor - "The constructor Expression(String) is undefined"
    Could you help me?

    1. Hi,

      Thanks for sharing opinion! 🙂 In case of your problem - looks like IDE issue. Have you been trying to recreate / refresh the project?

      Best regards

  18. Hi Mariusz,
    Ma
    I have a query regarding the usage of mxparser. We need a parser which works for both dotnet and objective-c. I know mxparser works for dotnet provide.
    Let us know whether mxparser supports objective-c.
    I do not see documentation for objective-c.

    Best Regards,
    Madhu.

    1. Hi,

      Unfortunately Objective-C is not supported. Library binaries are provided for JAVA and .NET/MON, including Xamarin.iOS. The only option to use mXparser on iOS is through JAVA or MONO (MONO meaning Xamarin.iOS).

      Best regards

  19. Hi Mariusz,

    first: thanks for this great library! It is nearly perfect!
    second: I have a problem with the following expression:

    Expression ex = new Expression("1-0200"); //=-199 // problem with preceding zero

    In version 3 of your library everything runs fine and syntax was correct; after upgrading to your latest version the method checkSyntax returns false. I ran threw your sourcecode, but I can't figure out the position which I have to change.
    Do you have any idea where I have to look or what I have to change?

    Thanks
    Theodor

    1. Hi Theodor,

      Thanks for your feedback. Indeed i changed the grammar cleaning some patterns in regular expression. This is impossible to reverse without JavaCC. Please let me know your use case, why you need this leading '0' - If you have reasonable arguments I may consider allowing leading zeros.

      Best regards

  20. Hi Mariusz

    Can I use the "AND" operator except for the operators "&", "&&", "/ \\" .
    for example: Expression e = new Expression(" 3+2=10") ;
    I've tried to change boolean operator && on a "AND" but don't this work.

    Thank's

    1. Hi Petr,

      Currently unfortunately not. But still you have 3 additional tokens for boolean AND operation.

      Best regards

  21. The parser is truly amazing, it's exactly what I needed! I was just wondering if there was a way to represent large numbers in a normal decimal form rather than in a scientific form when doing calculations?

    1. Thx Anon for your feedback 🙂 It is really important to me 🙂

      In terms of very large numbers, in upcoming mXparser v.4.1 "Aeries" you will get full support for scientific notations + other numeral systems with different bases.
      https://github.com/mariuszgromada/MathParser.org-mXparser/milestone/1

      Referring to your problem - you always can input very large numbers directly (without scientific notation), but the output is always type double. In v.4.1 I will introduce some simple / nice function to format double as string, but still double will have its own limitation regarding numbers representation (meaning loosing precision on very huge numbers).

      Best regards

      1. Thanks for the reply, secondly one of the other issues is that a string like "3pi" will evaluate to NaN, instead of 3*pi. This goes for all other symbols and functions too, ie, "5sin(50)" evaluates to NaN. Can you also please address this in your update?

        Lastly I've noticed that Logs and natural Logs of powers of multiples of 3 do not evaluate to precise numbers. ie, Log(1000) is 2.99999998 instead of 3, and Ln(e^6) is 5.999998 instead of 6.

        Best Regards

        1. "3pi" this is implicit multiplication, currently this is syntax error. I have doubts with introducing implicit multiplication... as this might be confusing. Byt will think on that.

          Can you let me know what framework are you using (java, .net, ...)? mXparser is for numerical computation, not symbolical, and this small "rounding" error might occur. For java "ln(e^6)" gives perfect 6.0

          Best regards

          1. I'm using Java,
            This is my code:
            ----------------------------------------------------
            Expression e = new Expression("log(10,1000)");
            String ms = String.valueOf(e.calculate());
            System.out.println(ms);
            ----------------------------------------------------
            The output is 2.9999999999998

Leave a Reply

Your email address will not be published. Required fields are marked *