MathParser.org-mXparser has been downloaded more than 4.000.000 times!
TO SUPPORT MY WORK, ORDER A COMMERCIAL LICENSE
THANK YOU!
Tutorial Math Collection API spec Download
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.
This parser is great, I am using it to my thesis project where solving user input formulas is the goal.
Thanks a lot!
Leroy
Thanks 🙂
Hi Mariusz Gromada,
I was looking some help to make something like this but not like yours, yours is awesome, I stopped looking any further code. Can I get your permission to use your tool in my project.
Please send me a confirmation to my email as don’t want to violate any copyright law.
Thanks
Murad
Yes you can 🙂 mXparser is distributed under simplified BSD license, it means that you can use it without limitations. The only condition is to put somewhere information that you are using mXparser, i.e. in case you provide license, then please reproduce also license of mXparser.
Best regards
did you get permission
How to solve a multi-line equation e,g
x+y=4
2x+3y=7
i need the value of x and y
x+y = 4 is ambiguous, it gives infinitely many solutions. What do you mean to solve x+y=4?
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!
Thanks 🙂
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?
Thank you for your message. Of course I will be happy to help 🙂 I will contact you directly via email.
Best regards
getArgumentValue() should be fine here, can I ask for some code example?
BR,
Mariusz
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
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.
Hello!
I need to show what he considered a derivative function.
This is so f(x) = x ^ 3 f(x) `= 3 * x ^ 2. How to do it? Can you help me?
Thanks a lot for this great work.
I found a problem :
Expression a= new Expression(“0.1+0.1+0.1”);
System.out.println(“Res : “+a.calculate());
result:
Res : 0.30000000000000004
……………………………………………
i think you can use bigdecimal instead of double.
more information:
http://floating-point-gui.de/
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
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
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
0.1+0.1+0.1=0.3 since 3.0.0 🙂
I found this today on the internet 🙂 Nice online calculator based on mXparser.
http://mxcalc.somee.com/
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!
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
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.
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
Really glad to see your reply. I am happy to wait for your update =)
Thanks,
Nat
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
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.
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
Hi here is me again
Do you have plan in implement complex number calculation?
Thanks that 🙂
I am thinking about that – but this is bigger change.
Best regards
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!
mXparser provides API for JAVA and .NET – I plan to keep this, so thinking about development I need to consider this.
Best regards
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?
Dear Michel,
Thank you for your feedback. Can you please provide more details on this specific use case?
Kind regards
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.
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.
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
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 )
Thanks! I will find and correct those bugs!
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…
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
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
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.
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
Hi Melwin,
Unfortunately (as of now) operations on strings are not supported.
Best regards
Oh! I see. Nonetheless, it’s a really good parser and also thank you Mariusz for your super quick responses!
– Melwin
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
Hi Akagra,
Thank you for your feedback. I will check and try to solve.
Kind regards
It seems this is related to stack issue. Lexer analysis has to be ok for getCopyOfInitialTokens – i will add checkLexerSytnatx() method.
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 ??
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?
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
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
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.
Hi,
Unfortunately – vectors are not supported.
Best regards
Thanks for your reply.
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.
How can I calculate an N root in an expression with C#?
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
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?
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
mXparser provides only numerical differentiation – it means you can calculate the derivative value.
Thank you Mariusz. Your lib is great!!
Hello,
Thank you for making your parser freely available! I’m using it in a (free) Android app: https://play.google.com/store/apps/details?id=atorch.statspuzzles.
Cheers,
Adrian
Thanks for sharing! Great! 🙂
Someone who uses the app found a bug: 1!^1 appears to crash the parser. Has this been reported before?
It was fixed in v.4.0, current version is v.4.1, pls see the issue details
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/17
Which mXparser version are you using?
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?
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
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.
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
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
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
Support will be added again in 4.1
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/36
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
Hi Petr,
Currently unfortunately not. But still you have 3 additional tokens for boolean AND operation.
Best regards
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?
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
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
“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
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
For base 10 logarithm you also have log10 function.
Fixed, added automatic rounding on final result if result is very similar to the int
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/69
Hi Mariusz,
Thanks for developing the parser! I’m using it in this Android app I made: https://play.google.com/store/apps/details?id=com.kumailn.calculator
Regards,
Kumail
Thx for sharing 🙂
Hi Mariusz,
thank you for this great library. I now build an App Inventor extension to use your library in App Inventor projects. For more information about App Inventor see here http://appinventor.mit.edu. See the extension here: https://puravidaapps.com/math.php
Kind Regards,
Taifun,
puravidaapps.com
Hi,
Thank you for this feedback – I am very happy mXparser helped 🙂 Thank you for sharing the links!
Kind regards,
Mariusz
Hi Mariusz,
I’m developing in VB.Net and testing mXparser. I always get the following error when I try to evaluate a simple formula.
“System.IO.IOException” in mxparser.dll
The error occurs 4 times for every formula. I use the following code:
Imports org.mariuszgromada.math.mxparser
Public Function Evaluate(ByVal pstrFormula As String) As String
Dim oExpression As Expression
Dim dblExpression As Double
oExpression = New Expression(pstrFormula)
dblResult = oExpression.calculate()
pstrFormula can be any formula, like “1+2”.
Seems straightforward, but at the last line I get the error 4 times.
Do you see anything I’m doing wrong here?
Thank you,
Anders
Sorry, of course the declaration is
Dim dblResult as Double
This works fine:
Hi Mariusz,
thank you for your answer!
As far as I can see your solution, starting with “Dim oExpression As Expression”, is exactly what I’m doing. And yes: after “dblResult = oExpression.calculate()” the correct result is stored in “dblResult”.
But nevertheless the error “System.IO.IOException in mxparser.dll” is thrown 4 times at that line. I see it in the debugging window when I step through the code. So I think, if I’m not doing anything wrong, there must be a reason why mXparser throws that error. Even if it returns the correct result.
Aside from this error: as far as I can see mXparser is a very fine peace of work. Thank you!
Anders
Thanks. What version of mXparser are you using?
This is not a bug, this is the way how JavaCC was designed, and then ported to C#. In auto-generated code of the parser the throwing / catching System.IO.IOException is very common.
The impact on the performance might be only in DEBUG mode, but still very limited, as you can use “Just My Code” option.
Hi Mariusz,
Can you please help me ? I need to create functions, for example:
highest(volume,3) : return the highests 3 values stored in a XML file.
If the user enter highest(volume,3) in the system, the program need to identify this function. Can you please tell me if this is possible with mXparser ?
Greetings from Brazil!
Hi Phelipe,
This is possible. You have to implement FunctionExtension interface to read the value from XML file. Then using implemented FunctionExtension you are just creating user defined function. Plese refer to the example #5 “Case 5: Implementing your own Function Extension” in “User defined functions” section of mXparser tutorial.
http://mathparser.org/mxparser-tutorial/user-defined-functions/
If this helps – please start the repo in GitHub 🙂
https://github.com/mariuszgromada/MathParser.org-mXparser
Best regards from Poland (currently on vacation in Spain – Canary Islands)
Hi Mariusz,
Can you please help me ? I need to get g(x) from f(x)=0.
For example
f(x) = x^2 − x − 2 = 0,
g(x) = x^2 − 2,
g(x) = 1 + 2/x,
g(x) = (x^2 + 2)/(2*x − 1)
g(x)=x
g(x) actually what is x
Hi,
I think I do not understand your question… Is the question about mXparser? It is not clear what your are trying to solve.
Best regards
Hi Mariusz
I’m also getting the IO Exception every time I calculate. (Same as Anders 1 August 2017)
The answer is correct but the throwing and catching of the exception causes the system to run quite slowly especially if I’m doing a large number of calculations.
I’m using version 4.1
Further investigation into the source code, I have found that the exception is coming from the SyntaxCheckerTokenManager.
Its trying to call BeginToken on the input_stream but it has been disposed and thus will throw an exception and in the catch statement handle the defaulting etc.
Though this is quite unnoticeable when calling calculate() once. It has a tremendous impact on performance if you are using the parser to calculate numerous times.
Issue was registered on GitHub
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/86
This part is auto-generated by CSJavaCC – C# port of JavaCC.
This is not a bug, this is the way how JavaCC was designed, and then ported to C#. In auto-generated code of the parser the throwing / catching System.IO.IOException is very common.
The impact on the performance might be only in DEBUG mode, but still very limited, as you can use “Just My Code” option.
Hi Mariusz, Could you please explain, why does this expression give an error?
Time to time I may have variables with leading zeros, and this is what I got:
[1000+0001000] checking …
[1000+0001000] lexical error
Encountered ” “0 “” at line 1, column 7.
Hi,
Which version of mXparser are use using? Leading zeros are supported since 4.1.
Best regards
Hi,
You are right. I’ve been using 4.0
4.1.1 works well 🙂
I had old version , coz I followed your links here http://mathparser.org/release-notes/mathparser-org-mxparser-on-maven-central/
Perhaps you could change it to mvnrepository.com ?
Hi Mariusz,
Is this parser is compatible with .net core 2. When the expression “if(sum(1,0,0,0,0) = 0,1,0) +if(sum(1,0,0,0,0) = 1,3,0) + if(sum(1,0,0,0,0) > 1,10,0)” it return NaN
Hi,
Please use checkSyntax() + getErrorMessage().
Best regards
Hi Mariusz,
I would like to thank you first for the wonderful tool!
One question: Can I change from rad to deg at the angle functions like sin (). I would like to write sin (45) and not sin (45 * [deg])
Hi,
This was already implemented, but not released yet – you can find the change on GitHub
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/87
Best regards
Hi Mariusz,
How can I use the derived functions to vb.net?
Dim e As Expression = New Expression(“cos(1) – der(sin(x), x, 1)”)
Console.WriteLine(“Res: ” + e.getExpressionString() + ” = ” + e.calculate())
Error: System.InvalidCastException: “Bringing the string” Res: cos (1) – der (sin (x), x, 1) “to the” Double “type is invalid.”
In vb.net you need to add ToString() to cast double to string
Dim e As Expression = New Expression(“cos(1) – der(sin(x), x, 1)”)
Console.WriteLine(“Res: ” + e.getExpressionString() + ” = ” + e.calculate().ToString())
Thank You!
1 more question: How to make that e.calculate() return the value in type of Decimal (1e-28)?
mXparser always returns double. You need to cast / convert to decimal. If you want such a big precision pls also use mXparser.setEpsilon(0)
Hi,
How do I show the equation or expression of math in my android . do we have any separate view or how?.. Iam developing an application of maths which we will show the questions and options as objective Q&A test. So how do I use This to show in my applilcation. If now can we use with webView ..(Suggest Plz..) thanks…
Hi,
mXparser works on strings, so any component using string will be ok.
Best regards
Hello Mariusz, One wish I had is to write a App for Android Systems. Now I’ ve done it. I wrote a little Calculator and use your excellent parser for the calculation part. I hope you’ll enjoy it. At the moment I had the BetaTest in Google Play store for Germany and Poland. You will find the App under the following link.
https://play.google.com/apps/testing/noSpy.taschenrechner
Hello Mariusz,
I wrote a little Calculator App for Android with your excellent parser. Thank you very much. Your parser helps a lot.
At the moment the App is in BetaTest. If you would like to see, what I am doing there please click the following link
https://play.google.com/apps/testing/noSpy.taschenrechner
epsilon ist set to 10E-299, and it works with Double very good.
Best wishes
Peter
I wrote the email false , sorry. Now it is correct.
Hello Mariusz,
I’m a little confused. I wrote a Comment a few hours before and I thought I had made an error. I couldnt see it. So I wrote a new Comment now. But now there is my formerly comment. Whats going on??
But no matter ….
Best regards
Peter
I’ve built up an management indicators app (java + angular web app) with you package (to help managing the university where I work in Brazil). Amazing work!!!
Unfortunately the app is protected by login and password so I cannot share with you.
Thx for the feedback 🙂 You can still share the app name and description 🙂
If you like the package github star would be nice 🙂
Best regards
I’ve just starred it in Github.
Thx 🙂
Mariusz, is “prod” a reserved word in mxparser? I tried to create a formula using this string with a parameter and it mark it as invalid. Well, if so, where can I get a list of the reserved words in mxparser?
BTW, I think this isn’t the right place to post doubts… is there a more appropriate channel for doing it?
The best place is the issue list on GitHUb
https://github.com/mariuszgromada/MathParser.org-mXparser
Yes, this is built-in keyword for product iterated operator. But you cna easily change it – there is an option for that.
mXparser.setToOverrideBuiltinTokens();
mXparser.setNotToOverrideBuiltinTokens();
mXparser.checkIfsetToOverrideBuiltinTokens();
mXparser.modifyBuiltinToken(String currentToken, String newToken)
mXparser.modifyBuiltinToken(String currentToken, String newToken, String newTokenDescription)
mXparser.unmodifyBuiltinTokens(String… currentOrNewTokens)
mXparser.unmodifyAllBuiltinTokens()
mXparser.getBuiltinTokensToModify()
mXparser.removeBuiltinTokens(String… tokens)
mXparser.unremoveBuiltinTokens(String… tokens)
mXparser.unremoveAllBuiltinTokens()
mXparser.getBuiltinTokensToRemove()
Best regards
Thanks, man! Once more: great job!
How can i use mXparser with android studio?
Just grab the jar file and copy it into the libs folder, then add dependencies.
Great Work Mariusz !
Is there way in this library to replace patterns such as (#1 * #2)/#3
when passed a Map (“1”,25) (“2”,2) (“3”,10) should return 5
Thanks
Peter
Why not to use arguments?
Argument x1 = new Argument(“x1”);
Argument x2 = new Argument(“x2”);
Argument x3 = new Argument(“x3”);
Expression e = new Expression(“(x1 * x2)/x3”, x1, x2, x3);
x1.setArgumentValue(25);
x2.setArgumentValue(2);
x3.setArgumentValue(10);
mXparser.consolePrintln(e.calculate());
x1.setArgumentValue(20);
mXparser.consolePrintln(e.calculate());
Result:
[mXparser-v.4.2.0] 5.0
[mXparser-v.4.2.0] 4.0
The other option is via function, i.e.
Function f = new Function(“f(x1, x2, x3) = (x1 * x2) / x3”);
mXparser.consolePrintln(f.calculate(25, 2, 10));
mXparser.consolePrintln(f.calculate(20, 2, 10));
Result:
[mXparser-v.4.2.0] 5.0
[mXparser-v.4.2.0] 4.0
Bes regards
Great product Mariusz!
I am wrapping mXparser (Java version) with restful web service code to create “calculation services”. These can be accessed by other applications or standalone, with a web browser or http requesting tool. I work for a scientific laboratory and by using this I can pull all the calculations out of the code of the various existing applications and put them all in one place for auditing and cataloging purposes.
So far it is working great and I really like it. I did encounter an issue when working with very small (and probably very large numbers), however. If I run this Java code, using ordinary Java double’s (not even BigDecimal’s):
double ad1 = 2500;
double ad2 = 1.0013826583317465947599675784203E-15;
double ad3 = 30;
double ad4 = 35;
double ad5 = 40;
double ad6 = 1;
System.out.println(“ad2 = ” + ad2);
double calc = ((ad1 * ad2) / (ad3 * ad4 * ad5 * ad6));
System.out.println(“calc = ” + calc);
As expected, I get this output:
ad2 = 1.0013826583317466E-15
calc = 5.960611061498491E-17
However, when I try to do the same thing in mXparser:
Function function = new Function(“S(a1,a2,a3,a4,a5,a6) = (a1 * a2) / (a3 * a4 * a5 * a6)”);
Expression expression = new Expression(“S(a1,a2,a3,a4,a5,a6)”, function);
Argument a1 = new Argument(“a1 = ” + ad1);
Argument a2 = new Argument(“a2 = ” + ad2);
Argument a3 = new Argument(“a3 = ” + ad3);
Argument a4 = new Argument(“a4 = ” + ad4);
Argument a5 = new Argument(“a5 = ” + ad5);
Argument a6 = new Argument(“a6 = ” + ad6);
expression.addArguments(a1, a2, a3, a4, a5, a6);
System.out.println(“mxParser result = ” + expression.calculate());
I get zero back:
mxParser result = 0.0
Am I using mxParser correctly or is this a limitation? It seems like it should be able to handle these numbers, especially since the top code works with Java doubles.
Thanks very much,
Mike
Hi. Thx for your feedback. It is related to default almost int rounding. v.4.2 will introduce new options for that, see the github issues:
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/116
As of now – run this:
mXparser.disableUlpRounding()
mXparser.setEpsilon(0)
Pls let me know how it works.
Hi Mariusz,
Thanks very much for your reply. What you gave me didn’t work but when I switched it to this:
mXparser.disableUlpRounding();
mXparser.setEpsilon(.0000000000000000000000000000000000000000000000001);
It works. Thanks very much!
Mike
Hi Mariusz,
I need some help regarding the usage of the mXparser.
I would like to use it with mingw compiler (gcc (i686-posix-dwarf-rev0, Built by MinGW-W64 project) 5.3.0) .
My question is where can I find the appropriate lib dll and header files for build the mXparser into my project?
Thanks in advance.
Best regards,
Attila
mXparser is written in Java and the ported to C#. This is not C/C++ project.
Best regards
Hello Mr Gromada, thank you for the useful product you are developing.
I wanted to ask how can i solve 3(x-5)=2x+6 with mxparser in android?
Expression d = new Expression(“solve(3*(x-5)=2*x+6)”);
double c = d.calculate();
Toast.makeText(getApplicationContext(),”Solution “+c, Toast.LENGTH_LONG).show();
The code above did not worked.
Hi. Thx for your feedback. Please follow the code examples given in the tutorial.
http://mathparser.org/mxparser-tutorial/solving-equation-fx-0/
Best regards
If you want to solve f(x)=0 please use
solve( f(x), x, a, b)
where x is argument, [a,b] is the interval where the root is.
This is numerical solve, so you need to give a and b. In your case
solve( 3*(x-5) – (2*x+6) , x, -100, 100)
should work 🙂
Thanks.
Can i use
solve( 3*(x-5) – (2*x+6) , x, -infinite, infinite)
becasuse we don’t know solution interval.
Unfortunately no – this is numerical solve, this is not algebra parser.
Hi. I wanted to ask a question. I have a list of arguments. Is there any option that we could populate a dictionary with all the possible arguments and the parser could then evaluate the algebraic expression based on the values in the dictionary. (My list of arguments are user defined. I cannot hard code.) Thanks.
Hi,
Please check the tutorial, section on user defined arguments.
http://mathparser.org/mxparser-tutorial/user-defined-arguments/
Best regards
What if the number of arguments are different after each instance.
i.e. For first time: x,y,z
For Second time: r,t,y
I does not matter. Pls share a piece of code – then I will help you.
Hi, could you upload a version 4.1.x which has checkSyntax() method in Function working. Non of currently uploaded version on maven central have this method working and I’ve seen that bug has been fixed on gitHub in one of recent commits. Thank you!
Yes, I have a plan for that. But this will be 4.2, not 4.1, as the change was made only in 4.2 src.
Hi,
Do you have any plants to support vector/arrays?
I means that an expression will get nXm (n arguments for m different calculation)
and return double[] of m answers?
Hi Mariusz,
I am writing program in C# using your library but I have problem with n-th derivative.
Code:
Argument x = new Argument(“x”, 2);
Expression e = new Expression(“dern(x^3, 2, x)”,x);
mXparser.consolePrintln(“e: ” + e.calculate());
Output:
[mXparser-v.4.1.1] e: -8.796093022208E+16
As you can see the result incorrect.
Could you kindly tell me where I am making a mistake?
Thanks.
I suppose there is a bug in dern operator, for second derivative you can use this one
Argument x = new Argument(“x = 2”);
Expression e = new Expression(“der( der(x^3, x), x)”, x);
Or this one – this is shorter
Expression e = new Expression(“der( der(x^3, x, x), x, 2)”);
hello
im a beginner developer
im developing a scientific calculator android app for practice
as i found making a regular one so easy
i made a code that parse some of regular expressions
but i want more and it takes me too much time for it
i dont know how to impliment this program
can somebody help
and thank you for making this program it looks to me its very helpful
though i need help in how to use it in android studio
as i said im beginner
How can i evaluate ((STC-1 != WTC-3 || STC-1!= STC-1) || 9<= 8).
Here STC-1 and WTC-3 is a string.
PLease help.
STC-1 is calculated as STC – 1
You should name your argument as STC1
I would like to evaluate (STC-1 != WTC-3 || STC-1!= STC-1) || 9<= 8), but the problem here is the string part STC-1 and WTC-3 are string. I am not getting desired output.
Please help.
STC-1 is calculated as STC – 1
You should name your argument as STC1
I’m writing a virtual reality tool for data visualization and modeling, and needed an equation parser for comparing functions to data. This was just what I was looking for, and was drag and drop implementation into my Unity project. I really appreciate the C# support!
Thank you for your feedback 🙂
Hey Mariusz,
its possible to evaluate “nested” expressions?
Like the following:
var weightArgument = new Argument(“Weight”, “Length * Height”);
var result = new Expression(“Amount*Price*Weight”, constAmount, constPrice);
result.addArguments(weightArgument);
If I like to get ExpressionString I ike to get:
Amount * Price * (Length * Height)
Is this possible?
Thanks 🙂
Sure – see the code
var lengthArgument = new Argument(“Length = 2”);
var heightArgument = new Argument(“Height = 3”);
var weightArgument = new Argument(“Weight = Length * Height”, lengthArgument, heightArgument);
var constAmount = new Constant(“Amount = 4”);
var constPrice = new Constant(“Price = 5”);
var result = new Expression(“Amount * Price * Weight”, constAmount, constPrice, weightArgument);
Console.WriteLine(result.calculate());
lengthArgument.setArgumentValue(20);
heightArgument.setArgumentValue(30);
Console.WriteLine(result.calculate());
Best regards
Hi Mariusz, thanks for your answer 🙂
Yes I already know that I am able to calculate this.
But my wish is for info purposes to display the full formula.
I like to modulize it in code, but print all nested “variables”.
Its about: getExpressionString()..
It shouldn’t display Amount * Price * Weight.
It should display Amount * Price * (Length * Height) (Brackets are optional)
So. Automatically replace expression for Weight with given Argument.
You got? 😮 I saw in hidden properties, that there is a relation. I could build it by myself in my code, but I like to be ready for updates and I think it could help other people also.
no soy mucho de usar java…. pero estaba probando tu programa con ANDROID STUDIO, me parece genial tu mXparser, realiza un sin fin de cosas. pero me parece que debes de solucionar lo siguiente:
-b+5 (OK)
+b+5 (SE CUELGA EL PROGRAMA )
EL SIGNO “+” al principio de una variable provoca un cuelgue… pruebalo y me comentas
Gracias por la respuesta. Voy a probar y solucionar esto en un futuro muy cercano 🙂
Muy pequeño error, gracias. Ya corregido 🙂
Hi Mariusz,
I’m working on a virtual reality calculus educational app. I’m working with Unity and C#. I am trying to be able to graph implicit equations, i.e. “x^2+y^2+z^2-4=0”. My question is, if that was the equation that is input, how could I create a new function with everything but the “=0”. I need to be able to evaluate that function to see whether the value is +/-.
Thanks
Hi Randal,
Can you clarify a bit? “x^2+y^2+z^2-4=0” is the string provided by the end user? Does it always end with “=0”? There are many option to do that. Pls send more info and I will prepare a code snippet 🙂
Best regards,
Mariusz
Mariusz,
That is correct, the string will be input from the end user in that form. That is the most basic form of an implicit function. It will always end in “=0”.
Thank you
Randal,
I assume you want to evaluate z = f(x,y), so that f(x,y) – z = 0. I understand it might be impossible to ask user for the f(x,y), as in many cases finding f(x,y) might be hard. You just want an equation for the surface.
One possible approach is to set x and y values then solve numerically f(x,y) – z = 0 for argument ‘z’. Here we have few risks:
– there is not solution
– solution is not unique
But in general it will work.
mXparser provides ‘solve’ function – I can prepare a code showing how to do that.
In case when it is possible to ask the user for f(x,y) such that z = f(x,y) the whole issue is a lot easier.
Best regards,
Mariusz
I have been trying to post a question for a while but am not seeing it being displayed so i will try and ask here.
Please, how do i implement – cuberoot(27) – is there a function for this?
Its urgent please.
Thank you.
Please how do I implement 3√27 using this parser which is cube root function
I need some more information on how I can implement 3√27 which is the cube root of 27.
I check all the tutorials couldn’t find it
Please can I know how to implement 3√27 which happens to be cuberoot(27)?
Hi,
Pls use root(rootorder, number)
Best regards
Please, how do you implement, cuberoot – I have been going about it for days now.. I have used cbrt(27), 3sqrt(27) or doesnt the parser support cuberoot??
Thanks
Hi,
Pls use root(rootorder, number)
Best regards
Hello Mariusz,
Thank you very much for the greate library. I am using it for claculating simple formulas, in a a way that the user defines some parameters and writes the formula, and my application calculates it using mXparser.
Now I noticed -as the library is very powerful-, the user cannot define a parameter named “e”! I was wondering if it is possible to limit the library to simple basic math.
Thank you very much,
Yvonnila
Hi,
Thanks for your feedback. Please use below option
mXparser.setToOverrideBuiltinTokens();
It will trigger the behavior you expect, meaning keywords provided by the user will have priority.
If you just want to remove some keywords for the parser please use
mXparser.removeBuiltinTokens(list of tokens);
Please verify documentation.
Best regards,
Mariusz
Thank you very much for your reply!
Hello Mariusz,
Thank you very much for you powerful math library.
We are using it very often for complex Problems.
Unfortunately i have a Problem with the Digits.
When I use the e1.calcuate() function the double value it
Returns “only” has 14 after comma Digits.
When i calculate the same Expression in matlab i get 16 after comma Digits.
Is that a C#.toString Problem or where do i lose the precision?
Thank you very much.
Philipp
Tank you. Pls change the optipns. mXparser.disableUlpRounding()
mXparser.disableAlmostIntRounding()
mXparser.setEpsilon(0)
mXparser.setExactComparison()
Jest regards
Hi,
Thank you for this great library.
I’m using this library to make an Android app. It is available in the Google Play store. (CalcMat). Hope you will get happy seeing that your library is put to good use.
I have a question too.
How can i reduce the number of digits in the answer.?
Currently i get 16 digits after the decimal point. i want it to reduce to 12.
How can i do that?
Thank you
Hi Mariusz,
Thanks for sharing this powerful library with us.
I’m just wondering if you have a NuGet package that does not include the docs folder.
Thank you,
Calvin
Hi, thank you for your feedback. Nuget package was updated to no contain html documentation.
Best regards
Hi Mariusz,
Thank you very much for the library.
I’m using your library for calculation and also for checking if the string representation of the formula is correct. But for formulas “+2+3” and “2+3+” I got ‘true’ from checkSyntax() function.
Best Regards,
Elena
Can you share the code? Which version of mXparser are you using?
Hi, I installed the library using NugetPackage but when typing “using org. … ” it doesnt exist. Dont know whats the problem. Do i need to install something additionally ?
Using VS 2015 coding android app with xamarin
Did you use Install-Package MathParser.org-mXparser?
Hi,
First of all, You All did a great work in MXParser, Thanks for this,
I have a query, do we support underscore in number? As it is supported in java 7.
Like if we have expression like “.2/2.0+3-1*(5_000_000-3) + 7^2” then google calculates it properly. but with mxparser we are getting NAN as result.
Underscore in mXparser is used to recognize fractions, i.e. 1_3 = 1/3, 2_2_3 = 2+2/3
Best regards
Hello,
It is my first time using mXparser. I want to solve the equation: “x*tan(x) = y”.
So i’ll give a value to y argument and I want to get the multiples values of x.
Is this possible through mXparser?
Thank you in advance for your time.
Hi,
Please use “solve” functions, sample code below:
Argument y = new Argument(“y = 5”);
Expression e = new Expression(“solve(x*tan(x) – y, x, -pi/2, pi/2)”, y);
mXparser.consolePrintln(y.getArgumentName() + ” = ” + y.getArgumentValue());
mXparser.consolePrintln(e.getExpressionString() + ” = ” + e.calculate());
mXparser.consolePrintHelp(“solve”);
Result:
[mXparser-v.4.3.0] y = 5.0
[mXparser-v.4.3.0] solve(x*tan(x) – y, x, -pi/2, pi/2) = 1.31383772
[mXparser-v.4.3.0] Help content:
# key word type syntax since description solve( expr, a, b ) 4.0 f(x) = 0 equation solving, function root finding
– ——– —- —— —– ———–
223. solve
Best regards
Fantastic library! Thank you!
I’m writing an OBD2 library for car research, but have a small problem. It seems like the variable name C doesn’t work, always returns NaN. Is this intentional?
Argument C = new Argument(“C”, 0x7A);
Expression e = new Expression(“(C-40)/2”, C);
mXparser.consolePrintln(“Res 1C: ” + e.getExpressionString() + ” = ” + e.calculate());
outputs:
[mXparser-v.4.2.0] Res 1C: (C-40)/2 = NaN
Replacing that with A or B or D or X or Y all works:
[mXparser-v.4.2.0] Res 1D: (D-40)/2 = 41.0
Any idea?
Thank You!
You are trying to use reserved built-in keyword – ‘C’ is Binomial coefficient with syntax ‘C(n,k)’, please see the code below:
Argument C = new Argument("C", 0x7A);
Expression e = new Expression("(C-40)/2", C);
mXparser.consolePrintln("Res 1C: " + e.getExpressionString() + " = " + e.calculate());
mXparser.consolePrintln(e.checkSyntax());
mXparser.consolePrintln(e.getErrorMessage());
Result:
[mXparser-v.4.3.0] Res 1C: (C-40)/2 = NaN. expecting 2 arguments.
[mXparser-v.4.3.0] false
[mXparser-v.4.3.0] [(C-40)/2] checking ...
[(C-40)/2] (C) Duplicated
[(C-40)/2] (C, 1)
[(C-40)/2] errors were found.
You can easily fix that problem by setting the override built-in tokens option, please refer to the below code:
mXparser.setToOverrideBuiltinTokens();
Argument C = new Argument("C", 0x7A);
Expression e = new Expression("(C-40)/2", C);
mXparser.consolePrintln("Res 1C: " + e.getExpressionString() + " = " + e.calculate());
mXparser.consolePrintln(e.checkSyntax());
mXparser.consolePrintln(e.getErrorMessage());
Result:
[mXparser-v.4.3.0] Res 1C: (C-40)/2 = 41.0
[mXparser-v.4.3.0] true
[mXparser-v.4.3.0] [(C-40)/2] already checked - no errors!
Best regards,
Mariusz
Hi Mariusz ,
I was wondering if it is possible to write the formulas in other cultures. For example, having comma as the floating point seperator: 2,5 instead of 2.5.
Bests,
Yvonnila
Hi Yvonne,
Unfortunately not, the comma is a separator for function parameters.
Best regards,
Mariusz
Oh, thank you very much for your reply anyway 🙂
But … there is a possible workaround as mXparser provides additional function parameters separator – semicolon ‘;’
While you make sure that users will use ‘;’ instead ‘,’ in functions then you can use a trick 🙂 Please see the example below
String expStr = "2 + 3,2 - 2,3e10 + log(2;8)";
Expression exp = new Expression(expStr.replace(',', '.'));
mXparser.consolePrintln(exp.calculate());
Best regards
Oh! It seems that I have missed your reply!
Thank you for thinking about it, and for the workaround suggestion. I solved it in a similar way.
Bests,
Yvonnila
P.S.: I wish you a happy new year : )
Great library, was writing something like this, but yours is much better.
Question on using the solver. When there are multiple solutions, it seems that it randomly gives one of the possible answers.
Is there a way to make that systematic (like 1st answer from left to right), so I can have my software continue through the domain to find other possible solutions
Examples:
Code
Expression eee = new Expression(“solve(x^2+7.5*x-70.2,x,-100,100)”);
mXparser.consolePrintln(“Res. : ” + eee.getExpressionString() + ” = ” + eee.calculate() );
Called three times gives:
EVALUATE: solve( x^2+7.5*x-70.2, x, 100, -100) = -12.92946077
EVALUATE: solve( x^2+7.5*x-70.2, x, 100, -100) = 5.42946077
EVALUATE: solve( x^2+7.5*x-70.2, x, 100, -100) = 5.42946077
Thanks for considering
George
Never mind, I figured out how to write my own solver using this library that does what I wanted, so I’m good
Hi Can the Arguments be generated dynamically like below?
foreach (KeyValuePair variable in VariableDictionary) {
Argument x = new Argument(variable.Key + “=” + variable.Value);
}
if its possible how can they be used individually in Expression?
Expression e = new Expresssion(“SOMEEXP”, ????)
Hi Mariusz ,
I need to iterate through an array of number, pass it to a function and find the maximum number that came out of it. Do you have any idea how to solve this?
double[] factors = {0.5, 0.4, 0.3};
Argument arg = new Argument(“arg”, “max(f(iterate_factor));
Tried with the maxi, but maxi only iterates through fix number.
Hi Bryan,
There is a simple solution of your problem. You just need to implemented FunctionExtension interface – it is basically an option to create user defined function based on your java/.net implementation. Please find the code below.
Factor class get double[] as parameter. Function “factor” based on Factor class returns
factor(0) = length of an array passed in the constructor
factor(n) = array[n-1] for n
class Factor implements FunctionExtension {
double[] factors;
int index;
Factor(double[] factors) {
this.factors = factors;
index = -1;
}
@Override
public int getParametersNumber() {
return 1;
}
@Override
public void setParameterValue(int parameterIndex, double parameterValue) {
if (parameterIndex == 0) index = (int)parameterValue;
}
@Override
public String getParameterName(int parameterIndex) {
if (parameterIndex == 0) return "index";
return "";
}
@Override
public double calculate() {
if (factors == null) return Double.NaN;
if (factors.length == 0) return Double.NaN;
if (index < 0) return Double.NaN; if (index > factors.length) return Double.NaN;
if (index == 0) return factors.length;
return factors[index-1];
}
@Override
public FunctionExtension clone() {
return this;
}
}
And then function usage
double[] factors = {0.5, 0.4, 0.3};
Function factor = new Function("factor", new Factor(factors));
Function f = new Function("f(x) = x^2");
Expression e = new Expression("maxi( i, 1, factor(0), f(factor(i)) )", f, factor);
mXparser.consolePrintln(e.calculate());
+ result:
[mXparser-v.4.3.0] 0.25
Best regards
Hi Mariusz,
Super, it works great for me now. I have just one more question, is supporting BigDecimal is something that is on the roadmap of MXParser ?
Hi Bryan,
I am happy that t works. mXparser is flexible 🙂
In terms of BigDecimal – this is completely different story – currently there is no roadmap for that. It would require complete rewrite of the math libraries, as mXparser is based on the standard Math library. A lot of math functions are not present in BigDecimal.
The other issue is the problem to keep the same API for .NET and JAVA – mXparser currently supports exactly the same API for .NET and JAVA. There is no BigDecimal in .NET
Best regards
Mariusz , I’m glad and grateful to come across this mathParser. It works amazingly well for my demo.
(mXparser v.4.3.3)
Today I notice a interesting situation. That is the well-know “floating-point precision” problem.
2.53 + 2.0 … —> 4.529999999999999 where 4.53 is expected.
And I test the option “mXparser.enableUlpRounding() and disableAlmostIntRounding()”. They are not solving this probelm.
I debugged it . As in this example “2.53 + 2.0”, the operator is ‘+’,
and the corresponding source code invoked is “private void PLUS(int pos)”, in which the two arguments are directly added up (a.tokenValue + b.tokenValue),
not using BigDecial. And this is the source of this problem. And the method “setToNumber(pos, result, ulpRound)” can’t solve it and round it.
And I glance over the other posts here and your reply, I see there is not solution yet for this parser, as BigDecimal won’t be used, for compatibility reason. Hopefully, someday in new version this will be solved , making the parser perfact 😛
Hello , it says invalid module name when i try to run it
You need to pass more details.
Hi,
First of all thanks for this fantastic library.
iam experimenting this parser, is it possible to return array ? i see calculate function is returning computer double vale. is there support to return array.
Say i need to retun TopN numbers from the given input. It the input list is {70,20,40,80} and the for Top2 i need to return {80,70}
Hi,
mXparser does not support array as return type. You can still solve your problem pretty easily, just use user defined variadic function with ‘par’ token
Syntax
f(…) =
par(n) – returns parameter value at ‘n’
par(0) – returns parameters number
[npar] – the same as par(0)
See the below example, that solves your problem by returning n-th number from provided list. Just make a loop and create array later on
Function f = new Function(“f(…) = par( par(1)+1 )”);
Expression e1 = new Expression(“f(1, 10, 20, 30, 40)”, f);
Expression e2 = new Expression(“f(2, 10, 20, 30, 40)”, f);
Expression e3 = new Expression(“f(3, 10, 20, 30, 40)”, f);
Expression e4 = new Expression(“f(4, 10, 20, 30, 40)”, f);
mXparser.consolePrintln(e1.calculate());
mXparser.consolePrintln(e2.calculate());
mXparser.consolePrintln(e3.calculate());
mXparser.consolePrintln(e4.calculate());
mXparser.consolePrintln(f.calculate(1, 100, 200, 300, 400));
mXparser.consolePrintln(f.calculate(2, 100, 200, 300, 400));
mXparser.consolePrintln(f.calculate(3, 100, 200, 300, 400));
mXparser.consolePrintln(f.calculate(4, 100, 200, 300, 400));
Result
[mXparser-v.4.3.0] 10.0
[mXparser-v.4.3.0] 20.0
[mXparser-v.4.3.0] 30.0
[mXparser-v.4.3.0] 40.0
[mXparser-v.4.3.0] 100.0
[mXparser-v.4.3.0] 200.0
[mXparser-v.4.3.0] 300.0
[mXparser-v.4.3.0] 400.0
Argument i = new Argument(“i”);
Expression e = new Expression(“f(i, 10, 20, 30, 40, 50, 60, 70, 80)”, f, i);
int n = 3;
double[] topn = new double[n];
for (int j = 0; j < n; j++) { i.setArgumentValue(j+1); topn[j] = e.calculate(); } for (double v : topn) mXparser.consolePrint(v + ", "); Result: [mXparser-v.4.3.0] 10.0, 20.0, 30.0, Best regards
Hi Mariuz,
Thanks for the quick response.
Iam trying to find solution for this
Expression e = new Expression(“add(tee1,tee2)”);
e.defineArgument(“tee1”, 70);
e.defineArgument(“tee2”, 80);
e.calculate(); //prints 150.0
but it it is
Expression e = new Expression(“add(1,2)”);
e.defineArgument(“1”, 70);
e.defineArgument(“2”, 80);
e.calculate(); //prints NAN . It is not working
Here 1 and 2 are the ids whose values are 70 and 80 ..
If the arguments are numbers then it is not working…
Need your help on this
Thanks
Karthik
Hi Mariuz,
We used Expression
Expression e = new Expression(“add(tee1,tee2)”);
e.defineArgument(“tee1”, 70); e.defineArgument(“tee2”, 80);
e.calculate(); //prints 150.0
but can we use the expression arguments as Integers
Expression e = new Expression(“add(1,2)”);
e.defineArgument(“1”, 70); e.defineArgument(“2”, 80);
e.calculate(); //prints NAN . It is not working
because 1 and 2 are ids that will be replaced by their actual values.
Any workaround for this?
Hello everyone!
I´m looking for a way to simplify expressions like:
1) sum(x+5,x+2) = 2x+7
2) sum( x+5, min(2,x+7)) = min(x+7,2x+12)
The goal is to have a set of inequalities at the end of the day. So we dont know the actual value of x at any time.
Is there a way to work with variables without defining actual arguments for them?
Hello Marius,
mXparser is a great achievement and I am very interested in using it.
However, I have a problem that I am not able to resolve and I hope you can help.
First of all I would like to use your parser in a WPF project so I started a simple c# project with a window, a button, one text box to display the result of the calculation. Then I copied and pasted your examples into the button code and replaced the console output with the proper reference to the output textbox.
The code of Hello World worked fine however It didn’t with others. It seems that the problem is the keyword “Expression” that leads to this error:
Error CS0104 ‘Expression’ is an ambiguous reference between ‘System.Windows.Expression’ and ‘org.mariuszgromada.math.mxparser.Expression’
Copy&Paste of all the examples in a console application worked fine.
An additional note : will be great to have the code examples in visual basic as per Hello World.
Thanks for your help.
Best Regards,
Maurizio Verri
It seems like you have both System.Linq.Expressions and org.mariuszgromada.math.mxparser in usings and Expression is ambigous. Remove System.Linq.Expressions if it unnecessary or reference explicitly org.mariuszgromada.math.mxparser.Expression or use alias using Expression = org.mariuszgromada.math.mxparser.Expression
Thanks for the suggestions!
Now it’s working!
Hi Mariusz. Many thanks for creating, supporting and improving mXparser. It’s a terrific resource!
Perhaps I’m missing something obvious, but I’m getting unexpected results using mXparser (v4.3.3) in a C# / .NET Core UWP (v6.2.8) project. A simple two-argument expression seems to work just fine, as below:
Argument A = new Argument($”A = 1″);
Argument B = new Argument($”B = 2″);
expression = new Expression( $”B – A”, A, B );
result = expression.calculate();
// Successful result
// expression.errorMessage = “[B – A] checking …\n[B – A] no errors.\n”
________________________________________
However, the calculation returns an error in a simple three-argument expression:
Argument A = new Argument($”A = 1″);
Argument B = new Argument($”B = 2″);
Argument C = new Argument($”C = 3″);
expression = new Expression( $”C – B – A”, A, B, C );
result = expression.calculate();
// Error result
// expression.errorMessage = “[C – B – A] checking …\n[C – B – A] (C) Duplicated .\n[C – B – A] (C, 0) expecting 2 arguments.\n[C – B – A] errors were found.\nProblem with expression syntax\n”
________________________________________
The really strange thing is that when I run the same three-argument expression using argument names shown in the online tutorial (“User defined arguments”), the calculation is successful:
Argument x = new Argument($”x = 1″);
Argument y = new Argument($”y = 2″);
Argument z = new Argument($”z = 3″);
expression = new Expression( $”z – y – x”, x, y, z );
result = expression.calculate();
// Successful result
// expression.errorMessage = “[z – y – x] checking …\n[z – y – x] no errors.\n”
Not sure what’s happening here. I don’t see any restrictions in argument naming in the documentation. What am I missing? Is this behavior explained in the documentation?
Ultimately, I’d like to build fairly simple expressions of up five arguments using argument names A, B, C, D, and E. Is this possible?
Many thanks…Dan Meier
Dear Dan, thank you. You are using “C” keyword, which is as built in one for combinations. At the very begging please add this code: mXparser.setToOverrideBuiltinTokens()
Best regards
i am using the parser in app Inventor for android. unfortunately i found that number < 10e-13 are equal 0
for example 1e-7^2 =0 in display but internally it still works. how can i use scientific notation in app inventor?
i use the great xparser in the app inventor but find issues when numbers are less 1e-14. in that case the result is ZERO.
also i am not clear if the user defined constants are defined in that android developer.
for example
x=2
gives NaN
thanks
erhard
Mariusz, I’m having an issue rolling your library into a DLL that is used in another application environment. Using C#.
Setup is
1) Wrote custom DLL with a single static function eval expression using mxparser
2) Compiled DLL
3) Imported into other application to use
4) Get this error
System.IO.FileNotFoundException: Could not load file or assembly ‘MathParser.org-mXparser, Version=4.3.3.0, Culture=neutral, PublicKeyToken=0fbab7add73ed6e2’ or one of its dependencies. The system cannot find the file specified.
In anticipation of this maybe being a tricky problem (may take a few back and forths outside of these messages) I’ve already made a donation to the cause using the email address attached to this message.
Mariusz , I’m glad and grateful to come across this mathParser. It works amazingly well for my demo.
(mXparser v.4.3.3)
Today I notice a interesting situation. That is the well-know “floating-point precision” problem.
2.53 + 2.0 … —> 4.529999999999999 where 4.53 is expected.
And I test the option “mXparser.enableUlpRounding() and disableAlmostIntRounding()”. They are not solving this probelm.
I debugged it . As in this example “2.53 + 2.0”, the operator is ‘+’,
and the corresponding source code invoked is “private void PLUS(int pos)”, in which the two arguments are directly added up (a.tokenValue + b.tokenValue),
not using BigDecial. And this is the source of this problem. And the method “setToNumber(pos, result, ulpRound)” can’t solve it and round it.
And I glance over the other posts here and your reply, I see there is not solution yet for this parser, as BigDecimal won’t be used, for compatibility reason. Hopefully, someday in new version this will be solved , making the parser perfact
hi, thank you very much for this great features for dynamic calculation.
however i dont understand what could be wrong?
Dim eh As Expression = New Expression(“sum(123,123,4334,76867,8234,87867)”)
Dim var1 As String = eh.calculate()
Error message: [sum(123,123,4334,76867,8234,87867)] (sum,0) expecting 4 or 5 calculus arguments.
many thanks
patrick
how dump of me as i didnt see its iterated function.
Sorted it out, should use add instead.
many thanks
What about decimal fractions? When you write 2.5-2.3 it is 0.200000000000002, how fix it?
mxParser looks to be very good…. but I have a particular scenario where I don’t know ahead of runtime if an expression will be valid.
So I have a string, which could be an arithmetic expression or it could just be any old string.
I would like to be able to test the potential string expression to see if it is a valid expression, and if so then evaluate it.
Alternatively attempt to evaluate the expression and if it cannot be evaluated return an error, but not an exception.
The code can be evaluating many thousands of iterations and throwing an exception is too expensive in this situation.
Another requirement I have is for mxParser to be thread safe. Ideally I would like to inject a single instance of the parser rather than new up a parser for each thread.
Any information you can give me on this would be great.
Dear Rob,
Java or .net?
Generally – please use
Expression.checkLexSyntax() – if true then grammar is ok
Expression.checkSyntax() – if true then can be evaluated
Expression.calculate() – to calculate
Expression.getErrorMessage() – to print errors after checkSyntax or calculate()
mXparser does not throw any exceptions, but checking Syntax is quite costly
Please also follow the tutorial:
http://mathparser.org/mxparser-tutorial/inspecting-calculation-process/
http://mathparser.org/mxparser-tutorial/playing-with-expression-tokens/
mXparser in general is thread safe – you can run Expression.calculate() on various threads without any risk, each thread will read synchronized options for common mXparser class, especially you can invoke mXparser.cancelCurrentCalculation() from a different thread, the all threads will stop automatically.
An example of multi-thread implementation
https://github.com/mariuszgromada/MathParser.org-mXparser/blob/master/CURRENT/java/src/org/mariuszgromada/math/mxparser/regressiontesting/PerformanceTests.java
https://github.com/mariuszgromada/MathParser.org-mXparser/blob/master/CURRENT/c-sharp/src/org/mariuszgromada/math/mxparser/regressiontesting/PerformanceTests.cs
Best regards
I am trying to use a mXparser to generate some math problems for kids to practice with.
I am stuck on solve() function.
Tutorial has this example:
2x – 4 = 0
Expression e = new Expression(“solve(2*x – 4, x, 0, 10)”);
http://mathparser.org/mxparser-tutorial/solving-equation-fx-0/
Changing “2x – 4” to “2x – 2” returns 1, but changing it to “2x – 3” returns NaN, instead of expected 1.5.
Expression e = new Expression(“solve(2 * x – 3, x, 0, 10)”);
What are the 3rd and 4th parameters in solve function (0 and 10 respectively)?
Obviously I am misunderstanding something here. Could someone help?
Hi, solve is a numerical solving function, so
solve(f(x), x, a, b)
means that mXparser will search for a solution of f(x) = 0 in the range between a and b, meaning a <= x <= a I have just tested your example:
Expression e = new Expression(“solve(2 * x – 3, x, 0, 10)”);
It gives 1.5
Can you run this?
Expression e = new Expression("solve(2 * x - 3, x, 0, 10)");
e.setVerboseMode();
e.calculate();
mXparser.consolePrintln(e.getErrorMessage());
Best regards
Hi
Thanks, that works actually, I’ve set the upper limit to 1 while trying to figure it out…
Why are there limits? Doesn’t knowing the limits assume you know the solution, which defies the purpose of solve function? Is solve perhaps not the right function for these simple equations?
Also, is there a way to solve non zero functions, e.g. x + 4 = 7? Or do I have to convert it to (x + 4) – 7 = 0?
Regards
Dejan
Hi Mariusz, i would like to use this in a native c++ project… C++/CLI is not an option. Do you think this is possible? I would like to port the entire code to pure c++ or something… looking at the java src, it looks similar to c++ but it seems it uses javaCC.jar somewhere. I thought it was entirely java source… Would excluding the binary javaCC.jar cause complications?
Hi,
JavaCC is just to generate the parser, so If you port a generated code it should work. JavaCC is used just once when the grammar is being changed.
I would be happy to accept your port of mXparser in the github repository – can you do it like that?
This is the part of the code that was generated by the javaCC based on the jj file containing grammar definition.
https://github.com/mariuszgromada/MathParser.org-mXparser/tree/master/CURRENT/java/src/org/mariuszgromada/math/mxparser/syntaxchecker
Best regards
Hi, sorry for the late replay… No Problem with linking the port… I need some help, i can’t find any contact information on the site except this comment section…
For the past week(s) or so i have been slowly porting the library to c++… I need some help on the syntaxchecker classes just a few of the parts… the other classes conversion was successful(hopefully) but i need to have a successful build first to test if the results are the same with the original mathparser…
Hi Mariusz,
Thank you so much for this great calculator.
I am wondering if there is any function like TRUNC in oracle?
For example, round(100.346,2) = 100.35,
trunc(100.346,2) = 100.34.
Please help, thanks a lot!!!
Is this package can validate if the string is a valid expression or not? example is
“20*log(var1/var2)” this is valid
“20*log((var1/var2)” this is not valid.
Can we use if condition to check for string equality with mathparser?
Unfortunately it is not possible. Best regards
Hi Mariusz,
Thank you for this great tool. I’m using it to make my own claculator as a tutorial project so maybe I did something wrong but -4^2 returns 16 instead of -16 and -4^5.2 returns Nan. Can you please help me with that issue?
Thanks
-4^2 = (-4)^2 = 16
-4^5.2 = (-4)^5.2
generic a^x is defined for non-negative ‘a’
Best regards
Hi Mariusz,
I am thinking about using your parser for my project.
I need to hook it to several custom functions. One of them should get a string (variable name) as an input, and based on custom logic, return different values (decimal)).
How can I accomplish it using your parser?
Thank you in advance.
Max.
Can you provide more detailed example?
Hi Mariusz,
I’m writting you from the IT services in upv.es. We use your library in the sakai LMS product.
We have received a case of a teacher that has included a formula like this in an assessment
SQRT({ax}^2+{ay}^2+{az}^2)
And when ax,ay,az have the values of 2,-3,-2 like this
SQRT(2^2+-3^2+-2^2)
the calculate function in the Expression class is returning a NaN
hope this could help you.
Regards
SQRT(2^2+-3^2+-2^2)=SQRT(-9) is not a real number
SQRT(2^2+(-3)^2+(-2)^2)=SQRT(17) is correct
Hi Mariusz,
I’m looking to use your parser to perform various metrology calculation. I plan to enter the measure as constant and allow to define additional measure based on evaluation result of the additional user defined expression.
Can you tell me about the constant naming convention I should use?
What character are allowed in constant name?
What character are prohibited?
I’d like to achieve something such as:
MEASURE_NAME
MEASURE_NAME$NOMINAL
MEASURE_NAME$MAX
MEASURE_NAME$MIN
…
Or so.
Thanks and good job on the parser 😉
Is there a naming convention for constant?
Any non-reserved character I should use?
Hi Mariusz,
Thank you so much for your tool.
I am using your jar files for a basic android calculator development. Up to 7 digits, it gives expected results but when it’s cross the 7 digits, the results converted to the exponential format.
For example, input is : 1234567 result: 1234567.0(Expected)
but for the input 12345678 result: 1.2345678E7
Could you please tell me the process of how can I get the result 12345678 when my input is 12345678?
any solution for this ?
The result comes as double. Java/.net have their own default way to print the value (default to string conversion). Just use the proper double / float formater when you print the value.
Hi Mariusz,
I am using your functions inside Sakai platform to make calculated questions. As a statistic teacher it would be very helpful to have function for the cumulative distribution function and the quantile function (inverse cumulative distribution function) of the t, F and chi-squared distributions. These are the distributions related to the normal distribution and are important in statistical inference.
Thank you,
Isabel
Hi Isabel,
I have the same issues at Istanbul Kultur University. Could you get any response for your request or manage to solve how to use cdf functions within Sakai? Thanks.
Hi there, is there a workaround for double negative in the string, as this currently returns a Nan.
I.e: “1–1”
Result: Nan
Hi Mariusz,
I’m trying to figure out how to use only your parser to parse a string into a binary tree (or maybe linked list) because it would probably be easier for me to use a debugged parser than write my own (and then debug that).
Now I’m not so sure.
Is there a “hello world” for parsing the string:
“( marketDate != null && sellDate != null &&
(marketDate = getFirstDayOfNextYear() )” into a tree of it’s constituent terms?
Thanks!
Hi, please take check the Tutorial page:
http://mathparser.org/mxparser-tutorial/
particularly the section on expressions tokens:
http://mathparser.org/mxparser-tutorial/playing-with-expression-tokens/
Best regards
Ooh! I really like Case 2: Using tokens to print expression in a fancy way.
Thanks!
That is funny. I could have sworn I entered:
“( marketDate != null && sellDate != null && (marketDate = getlastDayOfNextMonth() || sellDate >= getFirstDayOfNextYear))”
At any rate, I played around a bit and ended up with some code (though not as clever as your “Hello World” calculation):
Expression condition = new Expression(“( marketDate != null && sellDate != null && ” +
“(marketDate = getlastDayOfNextMonth() || sellDate >= getFirstDayOfNextYear))”);
ArrayList initialTokens = (ArrayList) condition.getCopyOfInitialTokens();
for (int i=0; i=’ keyWord=’>=’ like=
18. token id=-1 level=2 string=’getFirstDayOfNextYear’ keyWord=” like=argument
19. token id=2 level=2 string=’)’ keyWord=’)’ like=
20. token id=2 level=1 string=’)’ keyWord=’)’ like=
So… how do I best turn that into a non-binary tree?
Presumably, the nodes will be something like:
class Node {
Token token;
List<Node> children;
}
But I’m not sure how to represent each subExpression, nor how to build the tree out of your parsed list, nor how to evaluate it in stages. Basically, as the arguments are instantiated, I’d like the system to “show it’s work” in stages, kind of like an explanation.
Any ideas?
Hi Mariusz,
I’m writing you from Istanbul Kultur University. My university uses Sakai LMS product and as a consequence your library. Thank you so much for your tool. I particularly use “calculated question” format in the exams which I believe it helps a lot avoiding cheating among students.
The problem is when I use some of the functions which is not listed in the examples, I got error messages that the function I used does not deliver numerical results. I am sure that with the range of values defined for my variables the result must exist. Sometimes it produces numerical results but then, without any notice, the question is locked for editing and I need to delete the question and prepare it from scratch. Can you give some advice so that I talk to IT people to make the necessary changes? Thanks again.
Assist. Prof. Okay ISIK
Industrial Engineering Department.
Hello!
Thanks for your message! Unfortunately I am not aware how Sakai wrapped my library, but still I can try yo help. Cam you give more specific examples?
Best regards
For example, when I tried to use the function below, the question is locked
{{a4}}=[[min({p1}, {x1})]]
I can use the below functions even if they are not listed in Sakai
[[({x3}#{x4})]]
[[{x3}={x3}|0]]
[[not(({x3}={x3})*({x3}=0))]]
[[max({p1}, {x1}, {x2}, {x3}, {x4})]]
I appreciate your help.
Thanks.
I do not not what is the role of the following chars: [,],{,}
mXparser support arguments, so in mXparser it can be used: max(p1, x1, x2, x3, x4) etc…
I assume Sakai substitutes particular values e.g. “{x1}” is replaced with the value in a string form. If this is the case I would recommend for Sakai to switch to user defined arguments.
It seems your problems are related to the way how mXparser was used in Sakai.
Best regards
Really appreciate your time, thanks.
Hola Mariusz, en primer lugar, gracias por este maravilloso analizador de expresiones.
Estoy usando su analizador para una calculadora (Android Studio);
String expresion = txt_operacion.getText().toString()
.replace(” “, “”)
.replace(“,”, “.”)
.replace(“÷”, “/”)
.replace(“×”, “*”)
.replace(“√”, “sqrt”)
.replace(“π”, “pi”)
.replace(“²”, “2”);
Expression exp = new Expression(expresión);
resultado = exp.calculate();
Me funciona bastante bien para cualquier tipo de operación que hago en la calculadora, aún así, e notado diferencias en rendimiento al procesar una expresión larga y con el uso prolongado de dos operadores en particular. Le explico;
Cuando en una operación larga, uso mucho los operadores “+” y “-“, el proceso de calculo se hace lento, lo que me extraña es que no me pase lo mismo con los operadores “*” y “/” .
A que podría ser debido esto?
gracias.
Hello Mariusz,
I have just completed the development of a simple java framework using mxParser features, called MXReflection.
The idea is simple, I have made the mxParser library features, available using Java POJOs.
You could find the details in the project Readme https://github.com/Ismail-Mekni/mxreflection
I am waiting for your feedback about the idea.
Thank you for your great work, it is so insightful.
Hello,
I would like to use your library to manage mathematical formulas. Store it in the db for runtime calculation.
But I have issue, about arguments. My formulas can have dynamic parameters in terms of numbers.
I don’t know how to manage it…
I read about uer defined viadiatic functions, but I don’t know how to pass those arguments in the code dynamically
You need to be more specific in description what you need. You want to define a function or you just need to calculate expression value based on the given arguments? Please give more examples 🙂
Best regards
Hello Mariusz,
I would like to define function, that would reside in database. This function, may have dynamic numbers of arguments.
During the runtime, my application, would read the function in the database and evaluate it.
For example: f1 stored in the database : f1(…)=(x*y)*3, x and y would be determined dynamically and set during the runtime…
After sometimes and for operational reason we change the definition of function to be f1(…)= (x*y)*2+z
also x, y, and z would be determined and set and set during the runtime.
I’m a beginner in mXparser, so please, forgive me if any misunderstanding.
It seems you do not need to use user defined functions. It is enough to use simple expression. For instance you just store expression string like “x^2+y^2-3+z”, then you have to recognize arguments and set arguments values.
Expression e = new Expression("x^2+y^2-3+z");
String[] args = e.getMissingUserDefinedArguments();
http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#getMissingUserDefinedArguments()
In the args you now have missing arguments names that needs to be defined and assigned.
Now read the tutorial on user defined arguments and you are done
http://mathparser.org/mxparser-tutorial/user-defined-arguments/
Best regards
Best regards
Thank you for your advice.
But, how to declare dynamically Arguments?
Assuming our expression may have dynamic number of parameters.
Yes,getMissingUserDefinedArguments() give us the name and the number of parameters. I thought about declaring and assigning Arguments as a list… However expression definition only take a list of Arguments separated with comma.
How to declare and set dynamic number of parameters to an expression?
Thanks for your assistance
Take a look here: http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html
Basically:
1) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#addArguments(org.mariuszgromada.math.mxparser.Argument…)
2) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#addConstants(java.util.List)
3) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#addFunctions(org.mariuszgromada.math.mxparser.Function…)
4) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#addDefinitions(org.mariuszgromada.math.mxparser.PrimitiveElement…)
5) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#defineArgument(java.lang.String,double)
6) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#defineArguments(java.lang.String…)
7) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#defineConstant(java.lang.String,double)
8) http://mathparser.org/api/org/mariuszgromada/math/mxparser/Expression.html#defineFunction(java.lang.String,java.lang.String,java.lang.String…)
9) and others …
Familiarize yourself with the API
Best regards 🙂
First of all, thank you for developing such a good software library, but I found a problem?
—————————————————————————————————
Expression eh = new Expression(“12+56-12/5-60”);
Expression ew = new Expression(“12+56-(12/5)-60″);
String a=ew.calculate()+””;
Log.d(TAG, a);
———————————————————————–
There is no negative number in the above formula
———————————————————————
correct
=5.6
In fact, the result is wrong
5.599999999999994
Thanks! This is not an error.
https://0.30000000000000004.com/
Do the same in java
double v = 12.0+56.0-12.0/5.0-60.0;
System.out.println("result = " + v);
result = 5.599999999999994
mXparser uses double precision math.
I have developed intelligent roudning procedures to avoid most of this cases, try this option in mXparser
mXparser.enableCanonicalRounding();
Expression e = new Expression("12+56-12/5-60");
System.out.println("result = " + e.calculate());
result = 5.6
Check other options in the API
http://mathparser.org/api/org/mariuszgromada/math/mxparser/mXparser.html
Best regards
mXparser.enableCanonicalRounding();
————————————————————-
Cannot resolve method ‘enableCanonicalRounding’ in ‘mXparser’
My software version is MathParser.org -Mxparser-v.4.4.0-jdk11.jar; is there any problem with my operation?
It seems that there is something wrong with my software version. I will update it to the latest library. thank
Thanks for the great library!
I want to use it as part of my software but currently it can’t all solve my functions.
This works fine:
solve(0.351567 * (x – 57) + 0.000000 – 2, x, 0, 255)
Result: 62,68881607
But for example, simple function 20317.600000/x = y
I know y (y = 22), I need to calculate x, so:
solve(20317.600000/x – 22, x, 0, 65535)
Result is always max value: 65535.
Your function at x = 0 is not defined, use different starting point, for instance 1 instead of 0.
solve(20317.600000/x – 22, x, 1, 65535)
Best regards
So, what exactly are last 2 values? Minimum & maximum or starting points?
Where is help/documentation of this?
https://mathparser.org/mxparser-tutorial/
https://mathparser.org/mxparser-tutorial/solving-equation-fx-0/
https://mathparser.org/api/
https://mathparser.org/mxparser-math-collection/
or use help that is built in the library
mXparser.consolePrintHelp();
mXparser.consolePrintHelp("solve");
Best regards
The last two arguments are: from, to
mXparser implements numerical root finding
Does someone have an implementation of (database/spring data/JPA) mapping between Variables, values of those variables and expression to be used by mxparser?
Hello Mariusz Gromada. Thank you very much for your efforts in providing mXparser for Java, .NET (Core) and mobile platforms. I used it both in Java and C#, great to have the same features with identical formula language.
Some time ago I started a new web application project, with Eclipse Microprofile (Java) and .NET Core microservices. The frontends get developed using TypeScript and the REACT framework. I do need the ability, to provide the users with a possibility to define mathematic formulas in an Excel-like way in the frontend. Most of the calculations must be done in Java or C# backend. mXparser was my first choice, but the frontend would not work. A JS-math framework like mathJS is nice, but formulas could be potentially different. My solution was to port your Java version to TypeScript. Examples in the tutorial calculate the same as your Java one. In conclusion, mXparser formulas can now be used in the JavaScript world (browser, nodeJS) too. Maybe you like the idea too. Feel free to contact me…
Hi,
Thanks for creating mXparser, it is extremely useful.
I wondered if you would be able to help for a particular use case:
I have a number of expressions to evaluate, each using a small selection from a fairly large number of variables, and the value of each variable may change before I need to re-evaluate each expression.
If I understand correctly, when I create each expression I need to addArguments(…) for each of the named arguments in the expression, and before evaluating each expression, I need to setArgumentValue(…) to update those values to the current value of the variable. In my case, this becomes quite a big overhead, keeping track of which variables are in which expression, and if I simply update every variable in my list it is quite inefficient. Is there a way to pass arguments in such a way that the values used by the parser update automatically when the underlying variable changes (i.e. a sort of pass-by-reference arrangement)?
Many Thanks,
Andrew
Thanks for creating mXparser, it is extremely useful.
I am consisdering integrating mXparser in my Onenote addin to allow for simple mathematical operations in an accounting environment where we use decimals with thousands and decimal separators.
I would like to be able to read the (selected) expressiong 1,200.15/250 and return something like 1,200.15/250=4.80.
I understand mxParser does not support thousands separators. Any hint on how to go about and implemnt that, or better if/when you would implement this?
Hello, great parser. Easy and containing a great number of math functions. Unfortunately, in my project, I have to use it also to parse expressions using math functions and operations on string and date data. I tried to define my string and date functions using FunctionExtension and FunctionExtensionVariadic, but they only work on doubles (in C#). Does mXParser support date and string functions?
Hey,
Nicely written. Calculators make our calculations very easy and it is time-saving and convenient way to get answer of the problem. There are so many online calculator available which makes your difficult problem of cross-product, matrices and many more by using cross product calculator , matrix multiplication calculator , slope intercept calculator and more.
Hi
is it possible to identify the type of error as a result of evaluation?
For example division by zero.
I was trying to get my functions to throw exceptions but the default implementation of the calculate doesn’t have that in the signature.
Estuve realizando un evaluador de expresiones matemáticas, similar a math.mxparser, y me encontré que con la expresión 2^2^2^2 no obtenemos el mismo resultado, ¿Es un error?:
EVALUADOR DE EXPRESIONES MATEMATICAS VB.NET
====================================
Fórmula = 2^2^2
math.mxparser = 16
mi evaluador vb.net = 16
Fórmula = 2^2^2^2
math.mxparser = 65536
mi evaluador vb.net = 256
Nota: MS excel calcula: 2^2^2^2 = 256
Estuve realizando un evaluador de expresiones matemáticas, similar a math.mxparser, y me encontré que con la expresión 2^2^2^2 no obtenemos el mismo resultado,
¿Es un error?:
EVALUADOR DE EXPRESIONES MATEMATICAS VB.NET ====================================
Fórmula = 2^2^2
math.mxparser = 16
mi evaluador vb.net = 16
Fórmula = 2^2^2^2 math.mxparser = 65536
mi evaluador vb.net = 256 Nota:
MS Excel calcula: 2^2^2^2 = 256
A couple of comments:
1) I found it difficult to uncover that mXparser supports the min() and max() functions. Maybe I missed it, but I didn’t see them listed in the API:
http://mathparser.org/api/
It was only by chance that I found them under the variadic functions:
https://mathparser.org/mxparser-math-collection/variadic-functions/
2) The clamp() function is a commonly used function; well by me at least. However, I didn’t see it listed in mXParser functions:
http://mathparser.org/api/org/mariuszgromada/math/mxparser/mathcollection/MathFunctions.html
I found myself having to define it myself using the user-defined functions class as:
“clamp(val,a,b) = max(a, min(b, val))”
How to multiply (5+5)(58+7) without asterisk “*” in the middle
Hello there,
and many thanks for creating this useful parser.
I use it in a small private project that composes chess problems with the help of an evolutionary algorithm (from the jenetics library), the math parser being used to enter and evaluate the fitness function (whose arguments come from regex-counting in the solution text of a problem).
Cheers
Hello,
There are some mistakes in the examples for the new functions cChi2, pChi2 y qChi2.
https://mathparser.org/mxparser-math-collection/binary-functions/
Thanks for these new functions.
Isabel
Dear Isabel,
Thank You! I have already fixed the problem
https://github.com/mariuszgromada/MathParser.org-mXparser/issues/266
Best regards
Hello i’m having problems with: sin(), cos(), tan() and arcsin(), arccos(), arctan(), log and ln. can you tell-me what is the problem?
———-
String userExp = display.getText().toString();
operacaoEfectuada.setText(userExp);
Expression exp = new Expression(userExp);
String resultado = String.valueOf(exp.calculate());
display.setText(resultado);
display.setSelection(resultado.length());
——-
ex:
sin(90)=0.8939966636005579 or arcsin(1) = 1.5707963267948966
cos(90)=-0.4480736161291701 or arccos(0) = 1.5707963267948966
tan(45) =1.6197751905438615 or arctan (1)= 0.7853981633974483
log(10)= NaN or log(1) = NaN
I am currently evaluating MathParser to be used in my user calculation code in my application and have found an issue with the updated version of the library (V5). I am using the getCopyOfInitialTokens() to find all the “argument” types in the equation and I am getting different results for the returned tokens when I use any of the 5.X.X versions of the library than I do when I use 4.4.3. The results from the function in version 5 seems to want to separate the tokens anytime that it finds the letter “e”. For example, using expression string “NewValue+OldValue” it returns the following in V5 (tokens separated by new lines):
N
*
e
wValu
+
OldValu
In version 4 using the exact same code it returns what I was expecting:
NewValue
+
OldValue
Hi
All details you will find here: https://github.com/mariuszgromada/MathParser.org-mXparser/issues/265
Basically in v5.0 implied multiplication has been introduced along with the option to switch it off.
Best regards
am evaluating mXparser for a new C# App (using VS2010, NET 4.0), basically this App has a number of values the user enters (ie: wall length in ft, number of corners, etc) which are then used to calculate multiple Product Qtys, each which uses a Formula to calculate the Qty, this is working, however, am wondering if I can speed up the processing time, have set the 3 Disable Rnd Functions (disableCanonicalRounding()) but the difference is negligible, being new am wondering if I’m missing something, not sure if you have any other pointers, let me know if you need more info
Thanks
Dear Andy,
Thanks for contacting. Your use case should work very fast. Most likely you are creating new objects to often. Please read below sections of the manual:
1) Expression pre-compilation: https://mathparser.org/mxparser-tutorial/expression-pre-compilation/
2) Smart rounding settings: https://mathparser.org/mxparser-tutorial/smart-rounding-settings/
3) Efficient calculation in the loops: https://mathparser.org/mxparser-tutorial/efficient-calculations-in-loops/
Best regards
Hello!
In the program, I calculate the value of a function using exp.calculate(). But how to ensure precision in 1e-28?
i am not able to use?
if(Name=”james”,1,0)
how can i use if string methods ?
mXparser operates only on numbers
Is there a possibility to define a function f(x) = y?
Yes, it is possible. In the case of the definition of f(x) = y, y acts as a constant, since the variable argument is x.
Constant y = new Constant("y = 2");
Function f = new Function("f(x) = y", y);
Argument x = new Argument("x = 1");
Expression e = new Expression("f(x)", x, f);
mXparser.consolePrintln(e.calculate());
y.setConstantValue(3);
mXparser.consolePrintln(e.calculate());
Hello, I’d like to ask how can I get all variable names in an expression, instead of using getMissingUserDefinedArguments()?
Hello Mariusz Gromada, i’d like to get step-by-step solution for an expression like
a = 2 + (3*10)
a = 2 + 30
a = 32
Hello @amit kamble,
you could check out the calculation step register:
https://mathparser.org/mxparser-tutorial/calculation-steps-register/
Is there a version for NET Framework 8 ?
If not, is there a date when it will be available ?
Thanks
Hello,
i would be interested to know if there is any way to parse a formula into seperate calculation steps. Example if there is a formula like: a*(b+c)/d would get parsed into something like this:
step 1: temp1 = b+c
step2: temp2 = a*temp1
step3: result = temp2 / d
I looked into the calc step register but it doesnt give me what i need.
Use case:
A user defined formula must be executed on a subsystem of the actual program (in this case a PLC). The plc can not parse the formula itself. Therefor an idea is that i pre parse the data for the plc so that it can do the simple calculations step by step without needing to parse the whole formula. This would also require the actual operation that is done in each step to be accessible as the plc should only do the basic operations (+,-,*,/,Pow,…)
Hi mxparser is great library for calculations.
https://www.linkedin.com/posts/activity-7250873102140616704-6PD_