Simplification in Symbolics

I am using the Symbolics package and having trouble figuring out how to simplify expressions. Note that \sqrt{3} and 3/\sqrt{3} are equal, but I can’t seem to get that. For example:

julia> using Symbolics

julia> a = sqrt(Num(3))
sqrt(3)

julia> a == 3/a
sqrt(3) == (3 / sqrt(3))   # this isn't helpful

julia> a - 3/a
sqrt(3) + -3 / sqrt(3)

julia> iszero(ans)
false           # this is incorrect

Looks like a bug, isequal(a, 3 / a) should return true or at least realize it can’t do the computation. isequal((3/a)^2, 3) also fails, but isequal(simplify((3/a)^2), 3) succeeds.

julia> a = sqrt(3)
1.7320508075688772

julia> 3/a
1.7320508075688774

Notiice the floating point error in the last digit arising out of dividing a rational by its irrational square root.

I’m not sure Symbolics.jl is really setup for this kind of work but maybe @ChrisRackauckas or @cryptic.ax can comment on that. You can do a similar trick as Symbolics.jl simplify exp(0) to 1 - #2 by langestefan

julia> using Symbolics

julia> a = sqrt(Num(3))
sqrt(3)

julia> rules = RuleSet([@rule(~x / ~s => ~x * ~s / (~s)^2)])
SymbolicUtils.Rewriters.Walk

julia> simplify(a - 3/a, rewriter=rules)
0

Which works because this rule is built in:

julia> sqrt(Num(3))^2
3

For my project, I’ve swapped out Symbolics for PySym. So I’m set, but I would have thought Symbolics should be able to do this sort of simplification without modifications.

You can use SymJ.jl. It is a Julia version of SymPy and faster than Symbolics.jl .

using SymJ
julia> a = sqrt(Sym(3))
sqrt(3)
julia> a - 3/a
0

Just for reference between isequal and == look at

Giac.jl doesn’t behave that way. (Just saying :smirking_face:)

julia> using Giac

julia> a = giac_eval(“sqrt(3)”)
or a = sqrt(to_giac(3))
GiacExpr: sqrt(3)

julia> a == 3/a
true

The link to the SymJ.jl announcement (though not yet registered) by the author @j_verzani, is

Yeah this is something Symbolics is not very good at. I think we can handle some of the trivial cases here (e.g. 3 / sqrt(3), 3x^2 * y / sqrt(3)) so I’ll set a bot on the problem. My only concern is if it will have a measurable runtime impact on / which is already pretty slow in SymbolicUtils. Benchmarks will tell.

SymJ.jl is pretty cool though, I’d definitely recommend giving it a shot. I’m also setting a bot on comparing some things I’m curious about, mainly design decisions that it has a different opinion on. If it gets registered, I think it might be a good backend for some of the polynomial expansion algorithms that Symbolics isn’t good at.

Also, the two expressions not comparing isequal is not really a bug. Symbolics’ expression canonicalization does leave a lot to be desired, but expressions only compare isequal if their tree structures (and corresponding types/shapes) are identical.

canonicalize sqrt/cbrt as rational powers. - Pull Request #1191 - JuliaSymbolics/SymbolicUtils.jl - GitHub should fix this.