Symbolics.jl: Simplify divisions assuming a variable is not zero

How can I use Symbolics.jl to simplify divisions assuming a variable is not zero?

For example, I would like to get 1 from

julia> using Symbolics

julia> @variables x
1-element Vector{Num}:
 x

julia> simplify(x / x) # How can this be simplified to 1 assuming that `x` is not zero?
x / x

For something as simple as the example above, I can use a custom rule such as

julia> div_rule = @rule ~x / ~x => one(~x)
~x / ~x => one(~x)

julia> simplify(x/ x, Rewriters.Prewalk(Rewriters.PassThrough(div_rule)))
1

However, if I have more complicated expressions, this doesn’t work anymore, e.g.

julia> @variables x y
2-element Vector{Num}:
 x
 y

julia> simplify(x * y/ x, Rewriters.Prewalk(Rewriters.PassThrough(div_rule)))
(x*y) / x

Something such as

julia> simplify(sin(y) * x/ x, Rewriters.Prewalk(Rewriters.Chain((
           @rule(~a1 * ~x * ~a2 / ~x => ~a1 * ~a2),
           @rule(~a1 * ~x       / ~x => ~a1),
           @rule(      ~x * ~a2 / ~x => ~a2),
           @rule(      ~x       / ~x => one(~x),
       )))))
sin(y)

seems to do the job, but it’s rather complicated and applies to all variables. Moreover, it doesn’t scale to more complicated expressions such as (x + y) / x.

  1. How can this be generalized to all forms of divisions mixed with other operations?
  2. Is there an easier way to achieve this?
  3. How can I restrict the simplification to some specific variables?

There’s simplify_fractions

2 Likes

Great, thanks!