mathics-core
mathics-core copied to clipboard
SymPy inserts Piecewise by default
Is your feature request related to a problem? Please describe. Not sure if this is a bug so much as a difference in default behaviour between SymPy and WMA. WMA tends to be a bit looser in making simplifying assumptions, whereas SymPy tries to enumerate all the possible cases. For example, for the expression:
Expand[Product[Sum[x^k, {k, 0, m}], {m, 1, 2}]]
WMA gives:
1 + 2*x + 2*x^2 + x^3
Whereas Mathics gives:
Piecewise[{{2, x == 1}, {1 + x, True}}]*Piecewise[{{3, x == 1}, {1 + x + x^2, True}}]
which causes some issues if e.g. you're trying to extract coefficients from the polynomial.
[!NOTE] In this case, the
Piecewisearen't actually needed, and are just a remnant of the fact that the intermediate expressionSum[x^k, {k, 0, m}]evaluates to (note the singularity at $x=1$)
Piecewise[{{1 + m, x == 1}, {-1 / (-1 + x) + x ^ (1 + m) / (-1 + x), True}}]So in this particular case
Simplifywill remove them, but in general SymPy does put them there for good reason.
Describe the solution you'd like
For compatibility with WMA, stripping the Piecewise from Sum et al by default. The easiest way to do that is to apply
sympy_result.replace(lambda x: x.is_Piecewise, lambda x: x.args[-1][0])
to the intermediate SymPy results, though it's perhaps worth doing something a little more intelligent than that. I had a look to see if SymPy has any existing hinting for avoiding generating them in the first place but couldn't find any.
However, the behaviour of SymPy here is quite useful when you care about making sure the results are defined everywhere, so it's good to keep it as an option. As far as I know the closest analogy in WMA is GenerateConditions, though it doesn't quite work the same - according to the docs, setting it to All is supposed to have the same behaviour as SymPy here, but it doesn't in my tests, and setting it to True yields
ConditionalExpression[(-1 + x^(1 + m))/(-1 + x), Element[m, Integers] && m >= 0]
which isn't quite the same.
Not sure if there's a better solution to align the behaviours of the two?
Describe alternatives you've considered
A possible workaround would be to implement PiecewiseExpand (I think the SymPy equivalent would be piecewise_fold), to at least allow the Piecewise expressions to be combined. But it's not exactly a full solution as it still results in existing WMA code that doesn't require that being broken.