Dominik Ficek
Dominik Ficek

Reputation: 566

Solve string linear equation

I have a linear equation in string format for example something like this:

equation = "2 * x + 1 = 17"

what would be the best approach to solving the equation for x?

Upvotes: 1

Views: 173

Answers (2)

Dan Getz
Dan Getz

Reputation: 18217

As another option, using Symbolics.jl:

julia> using Symbolics

julia> equation = "2 * x + 1 = 17"
"2 * x + 1 = 17"

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

julia> eqn = eval(Meta.parse(replace(equation, "=" => "~")))
1 + 2x ~ 17

julia> Symbolics.solve_for(eqn, x)
8.0

(not sure which equations Symbolics knows how to solve)

Upvotes: 1

Shayan
Shayan

Reputation: 6295

Here you go:

julia> using Roots

julia> f(x) = eval(Meta.parse("2 * $x + 1 - 17"))
f (generic function with 1 method)

julia> find_zero(f, 5)
8.0

(Thanks to my friend Elias, I learned this way to solve such problems).

Upvotes: 2

Related Questions