fkleon / math-expressions

A library for parsing and evaluating mathematical expressions, supporting real numbers, vectors, and basic interval arithmetic.
https://pub.dev/packages/math_expressions
MIT License
100 stars 35 forks source link

Evaluate roots written as fraction powers if base is negative #66

Closed edhom closed 2 years ago

edhom commented 2 years ago

The following equations are equal:

However, evaluating those for a negative x wont raise the same result. This is due to the IEEE standard for floating point arithmetic, which defines NaN for the case of a negative base and a non-integer exponent. Since this package is not about floating point arithmetic, but rather about mathematical equations, I would like to propose a fix for at least that case.

The following test succeeds with the proposed change.

test('root equivalence', () {
    final f = Parser().parse('(x^(2.0 / 3.0))');
    final g = Parser().parse('((x^2.0)^(1.0 / 3.0))');

    final contextModel = ContextModel()..bindVariable(Variable('x'), Number(-1));

    final result1 = f.evaluate(EvaluationType.REAL, contextModel);
    final result2 = g.evaluate(EvaluationType.REAL, contextModel);

    expect((result1 - result2) < 1e-10, true);
  });
edhom commented 2 years ago

@fkleon Did you have a chance to look at this already?:)

fkleon commented 2 years ago

Oops, somehow slipped through the cracks. Thanks for the detailed description, I'd be happy to include this fix.

Given that you already have a test case, could you add it to the actual unit test suite?

As a final note, this is a pretty specific case and there are of course limits, for example if second is not a division directly, but a more complex expression which may simplify further.

edhom commented 2 years ago

@fkleon Sorry for the late follow up. Thanks a lot! I added it to the Composite Function evaluation test. Hope this is fine:) And yes, I know this is very specific, but at least for our use case this seems to be sufficient, since this is how you typically express n-roots.

fkleon commented 2 years ago

No problem, thanks for your contribution and circling back to add the test. Have released this as 2.3.1 to pub!