JuliaSymbolics / SymbolicUtils.jl

Symbolic expressions, rewriting and simplification
https://docs.sciml.ai/SymbolicUtils/stable/
Other
524 stars 99 forks source link

Improve `simplify` rules for factorization #490

Open bowenszhu opened 1 year ago

bowenszhu commented 1 year ago
using SymbolicUtils
@syms x y z
expr = x * y + x * z
res = simplify(expr) # return x*(y + z). Good!
using SymbolicUtils
@syms a b c d
expr = a * b * c + c * a * d
res = simplify(expr) # return a*b*c + a*c*d. Bad!
(@v1.8) pkg> st -m SymbolicUtils
Status `~/.julia/environments/v1.8/Manifest.toml`
  [d1185830] SymbolicUtils v0.19.11

This looks simple, but is fundamentally important for generating computationally inexpensive functions.

mmikhasenko commented 1 year ago

I would be curious to know how it can be implemented properly.

One can craft the answer with a custom rule

r3 = @rule (~x)*(~y)*(~z) + (~x)*(~a)*(~b) => (~x)*((~y)*(~z)+(~a)*(~b))
#
@syms a b c d
expr = a * b * c + c * a * d
res = simplify(expr, RuleSet([r3])) 

but it is super specific and only works is the common term is the first in both.