问题
I have a text box and I simply type a mathematical expression like:
sin(1) + 2 + cos(5) + sqrt(5)
and pass it to my MathParser class object and it returns me the result.
I went through the class and found that for mathematical operators like +, -, *, /; there is a function which returns 2 because these operations can be performed only between two parameters like '1 + 2' and mathematical functions like sin, cos, tan, abs, sqrt; have a single parameter like sin(param), etc. so it returns 1.
Now, I want to add average function also, but problem is that when I type the expression avg(1+2+3+4), it gives priority to bracket first and add all the numbers, that's fine but for average I need the number of arguments passes within that function. I somehow managed to count for first average but what if it occurs with other functions or it occurs more than one time?
Is there any mathParser available which can have an avg built in function? I don't see it in Visual Studio Math class also.
回答1:
Yes, there is an open-source math parser supporting variadic functions (including average), which I was recently using in my project. The parser name is mXparser. Parser is implemented in C# and separately in JAVA.
https://mxparser.codeplex.com/
http://mathparser.org/
Your problem can be simply solved, please follow the below example
Simple average including variadic parameters
Expression e = new Expression("avg(2, 5, 6, 34, 2, 10) + avg(5, 4, 32)");
double v = e.calculate()
Simple average including variables in variadic parameters
Argument x = new Argument("x = 5");
Expression e = new Expression("avg(2, 5, 2*x, 34, 2, 10) + avg(5, 4*x, 32)", x);
double v = e.calculate()
Average as iterated operator
Expression e = new Expression("avg(i, 1, 100, i^2);
double v = e.calculate()
Best regards
来源:https://stackoverflow.com/questions/33958586/is-there-any-mathparser-that-parse-a-mathematical-string-expression-containing-a