Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solve_for gives Float64 instead of rational solutions #524

Open
knuesel opened this issue Feb 3, 2022 · 3 comments · May be fixed by #1136
Open

solve_for gives Float64 instead of rational solutions #524

knuesel opened this issue Feb 3, 2022 · 3 comments · May be fixed by #1136

Comments

@knuesel
Copy link

knuesel commented Feb 3, 2022

For example the following gives Float64 instead of rational values:

julia> @variables x y;

julia> Symbolics.solve_for([x + y ~ 2, x - y ~ 1], [x, y])
2-element Vector{Float64}:
 1.5
 0.5

julia> Symbolics.solve_for([x + y ~ 2//1, x - y ~ 1//1], [x, y])
2-element Vector{Float64}:
 1.5
 0.5

Here using rational coefficients makes no difference.

Note that the behavior depends on the values of the coefficients. Here's a case where using rational literals results in a mix of Rational and Float64:

julia> Symbolics.solve_for([x + y ~ 3, x - y ~ 1], [x, y])
2-element Vector{Float64}:
 2.0
 1.0

julia> Symbolics.solve_for([x + y ~ 3//1, x - y ~ 1//1], [x, y])
2-element Vector{Real}:
 2
  1.0

And here's one where a rational coefficient gives all-rational output:

julia> Symbolics.solve_for([x + 2y ~ 2, x - y ~ 1], [x, y])
2-element Vector{Float64}:
 1.3333333333333335
 0.3333333333333333

julia> Symbolics.solve_for([x + 2//1*y ~ 2, x - y ~ 1], [x, y])
2-element Vector{Rational{Int64}}:
 4/3
 1/3

┆Issue is synchronized with this Trello card by Unito

@ChrisRackauckas
Copy link
Member

@YingboMa you were looking into something around this yesterday?

@YingboMa
Copy link
Member

YingboMa commented Feb 3, 2022

Yeah, I am looking into this problem. The Symbolics.solve_for([x + y ~ 2//1, x - y ~ 1//1], [x, y]) example is arguably a bug.

@hersle
Copy link

hersle commented May 9, 2024

It seems to me that the issue is that the coefficients of x and y are automatically set to 1 under the hood, and not 1//1. To enforce that the coefficients become rational, multiply one (or both) equation(s) by 2 and make at least one coefficient rational, to "trigger" promotion to rationals during construction of the linear system A*x = B

using Symbolics
@variables x y
Symbolics.solve_for([
    2//1*x + 2*y ~ 4//1,
    x - y ~ 1
], [x, y])

gives

2-element Vector{Rational{Int64}}:
 3//2
 1//2

@hersle hersle linked a pull request May 9, 2024 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants