MatthewJA / Coffeequate

A computer algebra system for JavaScript.
http://matthewja.com/Coffeequate
MIT License
48 stars 8 forks source link

Expression.equals fails sometimes, expandAndSimplify is the culprit #117

Open MatthewJA opened 9 years ago

MatthewJA commented 9 years ago
var expr = CQ("a*x**3 - b = 0");
var sol = expr.solve("x");
sol[0].equals(CQ("(b/a)**(1/3)")); // false
sol[0].simplify().equals(CQ("(b/a)**(1/3)")); // true

So @expr.expandAndSimplify isn't fully simplifying. I'm not really sure why, but one possible (bad?) solution is to just keep simplifying until the expression no longer changes.

zvxryb commented 9 years ago

I'm not so sure that simplification is the right way to go about this, I just used what I had available. Maybe it should just expand instead? Distribute all power/multiplication terms so the expression tree is always (from top to bottom) "addtion > multiplication > power", then sort all terms so that you have a fully unambiguous canonical form.

MatthewJA commented 9 years ago

I think you're right, expanding makes sense. I'm not entirely sure expanding is going to give a canonical form, though (which seems to be the problem here anyway), so that'll need to be fixed. The simple solution is to call expand until the expression no longer changes, but that's pretty slow.

zvxryb commented 9 years ago

I started experimenting with writing a canonicalization function on this branch. It still needs work. There is currently an issue with distribution of division, which I find odd, because distribution of powers appears to work OK and division is just multiplication by Pow(base, -1).

My approach, so far, is as follows:

Also, although I wrote a separate implementation, I think there is some overlap between canonicalize and simplify (distribution, collection of like terms, etc.). As I see it, canonicalize is focused on unambiguous results, while simplify focuses on producing concise human-readable results. I think this makes simplify a superset of canonicalize which performs additional simplification, not necessarily respecting the above constraints.

MatthewJA commented 9 years ago

That looks really good! I'd definitely expect overlap between canonicalize and simplify, but possibly more overlap with expand. One idea that comes to mind is rewriting simplify and expand in terms of canonicalize, which I think makes a great deal more sense than the existing implementations of simplify and expand, so I might do that once.

But yeah, looks great so far!