0

I'm using the Java/.NET symbolic math library mXparser (5.0.2) to support user-provided math expressions in my app.

Problem

I found that the conditional clause iff does not support equality test, e.g.,

var f = new Function("f(x1, x2) = x1 + x2");
var g = new Function("g(x1, x2) = x1 * x2");
var k = new Function("k(x1, x2) = x1 - x2");
      
var h = new Function("h(x1, x2) = iff(x1 > x2, f(x1, x2); x1 < x2, g(x1, x2)); x1 == x2, k(x1, x2))", f, g, k);

e = new Expression("h(2, 1)", h);
mXparser.consolePrintln($"Res: {e.getExpressionString()} = {e.calculate()}");

e = new Expression("h(1, 2)", h);
mXparser.consolePrintln($"Res: {e.getExpressionString()} = {e.calculate()}");

e = new Expression("h(2, 2)", h);
mXparser.consolePrintln($"Res: {e.getExpressionString()} = {e.calculate()}");

This gives

[mXparser-v.5.0.2 bin NET6_0] Res: h(2, 1) = NaN
[mXparser-v.5.0.2 bin NET6_0] Res: h(1, 2) = NaN
[mXparser-v.5.0.2 bin NET6_0] Res: h(2, 2) = NaN

Workaround

I could turn to if clause to do something like

var h = new Function("h(x1, x2) = if(x1 == x2, k(x1, x2))", k);

But it's still annoying to use separate statements instead of an integrated expression.

Question

Am I missing something or is this by design?

kakyo
  • 10,460
  • 14
  • 76
  • 140
  • Hi, can you share the result of e.getErrorMessage() string? – Leroy Kegan May 02 '22 at 22:35
  • I run your code, result seems to be ok [mXparser-v.5.0.2 bin NET6_0] Res: h(2, 1) = 3 [mXparser-v.5.0.2 bin NET6_0] Res: h(1, 2) = 2 [mXparser-v.5.0.2 bin NET6_0] Res: h(2, 2) = 0 – Leroy Kegan May 03 '22 at 16:38

1 Answers1

1

Seems to work properly when I run below code:

Expression e;

var f = new Function("f(x1, x2) = x1 + x2");
var g = new Function("g(x1, x2) = x1 * x2");
var k = new Function("k(x1, x2) = x1 - x2");

var h = new Function("h(x1, x2) = iff(x1 > x2, f(x1, x2); x1 < x2, g(x1, x2); x1 == x2, k(x1, x2))", f, g, k);

e = new Expression("h(2, 1)", h);
mXparser.consolePrintln($"Res: {e.getExpressionString()} = {e.calculate()}");

e = new Expression("h(1, 2)", h);
mXparser.consolePrintln($"Res: {e.getExpressionString()} = {e.calculate()}");

e = new Expression("h(2, 2)", h);
mXparser.consolePrintln($"Res: {e.getExpressionString()} = {e.calculate()}");

Code result:

[mXparser-v.5.0.2 bin NET6_0] Res: h(2, 1) = 3
[mXparser-v.5.0.2 bin NET6_0] Res: h(1, 2) = 2
[mXparser-v.5.0.2 bin NET6_0] Res: h(2, 2) = 0
Leroy Kegan
  • 1,156
  • 10
  • 9
  • Thanks. I found my problem: In my actual code, I spell the `iff` expression wrong where I closed the parentheses too early before the equality test happens. But this was so confusing because not much error log showed up in the console. – kakyo May 03 '22 at 23:45
  • I updated my question to reflect that bug. – kakyo May 03 '22 at 23:47