根据标题,是否有可能解析和评估不等式以获得真/假结果?
举个例子:
Expression e = Infix.ParseOrThrow("A<B");它抛出:

我目前的方法是:
public static bool CheckInequalitySatisfaction(string inequality, BoxDimensionValues values = null)
{
try
{
if (string.IsNullOrWhiteSpace(inequality))
throw new ArgumentNullException(nameof(inequality));
if (inequality.ToLower().Equals("false"))
return false;
if (inequality.ToLower().Equals("true"))
return true;
var matches = Regex.Match(inequality, "(?<left>.+)(?<operand>==|<=|>=|<|>)(?<right>.+)");
if (!matches.Success)
throw new ArgumentException($"The inequality is not valid {inequality}", nameof(inequality));
var leftExpression = matches.Groups["left"].Value;
if (!TryEvaluateExpression(leftExpression, values, out int leftValue))
throw new ArgumentException($"The left expression of the inequality is not valid {leftExpression}", nameof(inequality));
var rightExpression = matches.Groups["right"].Value;
if (!TryEvaluateExpression(rightExpression, values, out int rightValue))
throw new ArgumentException($"The right expression of the inequality is not valid {rightExpression}", nameof(inequality));
var inequalityOperator = matches.Groups["operand"].Value;
return inequalityOperator switch
{
"==" => leftValue == rightValue,
"<=" => leftValue <= rightValue,
">=" => leftValue >= rightValue,
"<" => leftValue < rightValue,
">" => leftValue > rightValue,
_ => throw new NotImplementedException($"The operator {inequalityOperator} is not supported for inequalities evaluation"),
};
}
catch (Exception ex)
{
ex.Log(MethodBase.GetCurrentMethod());
throw;
}
}发布于 2021-06-10 22:02:48
我花了一些时间试图为您解决这个问题,但无法使用MathNet中的当前功能集。但我确实注意到MathNet的Expression对象可以处理其他Expression对象的+和-等操作,因此您可以编写一个扩展方法,将不等式转换为可解析的表达式。
基本上,由于我们知道Infix将解析"A-B“而不是"A
public static Expression SafeParseLessThan(this string mathExpression)
{
var splitExpression = mathExpression.Split("<");
var left = Infix.ParseOrThrow(splitExpression[0]);
var right = Infix.ParseOrThrow(splitExpression[1]);
return left - right;
}
使用用法:
var newExpression = "A<B".SafeParseLessThan();
var symbols = new Dictionary<string, FloatingPoint>
{
{"A", 3},
{"B", 5}
};
var result = Evaluate.Evaluate(symbols, newExpression).RealValue < 0; // true
考虑到您正在解析的函数的类型,您还需要考虑其他事情。例如,我快速创建的这个快速示例假设了真实的值。如果您需要在表达式中包含其他不可解析的元素,例如min和max,您还需要更有创造性,也许就像"min(A,B) < max(C,D)“中那样。
我还注意到你发布了与最小/最大函数的MathNet解析相关的another question。您可能也可以将这种类型的策略应用于此。
https://stackoverflow.com/questions/67309376
复制相似问题