Search code examples
juliasymbolic-math

With Julia Symbolics, can I solve for a variable in an equation?


I would like to solve for a in y = √((a^2 + b^2))

What I tried:

julia> using Symbolics

julia> @variables a b
(a, b)

julia> y = √((a^2 + b^2))
sqrt(a^2 + b^2)

julia> eq = y = √((a^2 + b^2))
sqrt(a^2 + b^2)

julia> eq
sqrt(a^2 + b^2)

And then to solve, I tried:

julia> Symbolics.solve_for(eq,[a])
julia> Symbolics.solve_for(eq,a)
julia> Symbolics.solve_for(y,[a])
julia> Symbolics.solve_for(y,a)

which all resulted in the error:

ERROR: type Num has no field rhs

Solution

  • There are two problems in your code. The first one is that an equation should have two parts, right hand side (i.e. rhs) and left hand side (i.e. lhs). Your error message clearly points out the problem: sqrt(a^2 + b^2) is a Num type since a and b are variables of Num since they will (supposed to) evaluate to numbers. In Symbolics.jl, the way to declare an equation is to use ~. So the right way to express your equation is

    @variables a b y
    eq = y ~ √((a^2 + b^2))
    

    However unfortunately Symbolics.jl cannot solve it for you now since solve_for can only resolve system of linear equations, just as the document says

    Currently only works if all equations are linear. check if the expr is linear w.r.t vars.

    So it will throw AssertionError: islinear(ex, vars) error. However you can try out this function using some simple equation like a+b.

    julia> eq = y ~ a+b
    y ~ a + b
    Symbolics.solve_for([eq],[a])
    1-element Vector{Num}:
     y - b
    

    BTW:

    You can turn off the linearity check with check=false parameter, but it's almost guaranteed that Symbolics.jl will give you a wrong result. For example, the Symbolics.jl says the result of equation y ~ √((a^2 + b^2)) is a + y*sqrt(a^2 + b^2)*(a^-1) - ((a^-1)*(sqrt(a^2 + b^2)^2)).