I have to find parser for solving equation with unknows. User enters two numbers and the parser parses equation to solve. For example:
Equation: x^3 y^2 sin60°
User input: x=4, y=2
It have to be done using AForge.NET framework. Console app/WinForms
I have been looking for it in AForge .NET documentation but can't find something matches my problem.
CodePudding user response:
I don't believe there is an evaluator for regular mathematical expressions in AForge, but you could use the PolishExpression class to evaluate an expression written in polish notation:
using AForge;
string expression = "$0 $0 $0 * * $1 $1 * " (Math.PI / 3) " sin ";
// variables for the expression
double x = 4;
double y = 2;
double[] vars = new double[] { x, y };
// expression evaluation
double result = PolishExpression.Evaluate(expression, vars);
Console.WriteLine("Polish expression evaluation: " result);
This yields the value 68.86602540378443. There's also no direct exponential operator, so I just multiplied x by itself three times. But you could use logaritms instead:
string expression = "$0 ln 3 * exp $1 ln 2 * exp " (Math.PI / 3) " sin ";
You can also confirm that this is the same as you'd get in C# (note that you must convert 60 degrees to radians in order to use Math.sin):
double TestEvaluate(double x, double y)
{
// x^3 y^2 sin60°
// Note that Math.sin accepts radians, so we must convert 60°
return Math.Pow(x, 3) Math.Pow(y, 2) Math.Sin((Math.PI / 180) * 60);
}
Console.WriteLine("C# evalution: " TestEvaluate(x, y));
But yeah, I'd recommend using another library if you don't want to use polish notation in your expressions.
I also tried the code example above with "AForge.Math.Expression", but I don't believe this class exists in AForge.Math 2.2.5.
CodePudding user response:
The AForge.NET framework includes several classes that you can use to parse and solve equations. In particular, the Expression class in the AForge.Math.Expression namespace can be used to parse and evaluate mathematical expressions. Here is an example of how you can use this class to parse and solve an equation with unknown variables:
using AForge.Math.Expression;
// Parse the expression
string equation = "x^3 y^2 sin60°";
Expression expr = new Expression(equation);
// Evaluate the expression with the given values for x and y
expr.Variables["x"] = 4;
expr.Variables["y"] = 2;
double result = expr.Evaluate();
// Print the result
Console.WriteLine(result);
This code will parse the given equation and substitute the values of x and y that the user entered, and then evaluate the expression to find the result.