sympy / sympy

A computer algebra system written in pure Python
https://sympy.org/
Other
13k stars 4.44k forks source link

Difficult to subs in Diophantine solutions #24128

Open jakoblem opened 2 years ago

jakoblem commented 2 years ago
from sympy import *
x, y = symbols('x,y')
sols, = diophantine(2*x-3*y-5,x)
sols[0].subs(x_0,4)

print(sols) is a tuple of (3*x_0 - 5, 2*x_0 - 5), however line 4 leads to NameError. One has to write sols[0].subs(Symbol('x_0', integer=True),4) as can be seen from srepr(sols[0]). Not exactly an error, but I think it will confuse many users.

bjodah commented 2 years ago

Can't you access the new symbols using .free_symbols?

jakoblem commented 2 years ago

Sure, one can do sols[0].subs(sols[0].free_symbols.pop(),4) but this is the same as sols[0].subs(Symbol('x_0', integer=True),4). The command sols[0].free_symbols.pop() prints $x_0$ without indicating that $x_0$ has to be accessed by Symbol('x_0', integer=True).

smichr commented 2 years ago

The symbol you pass is just used to create the name for the parameter. You don't have to know the assumptions on the parameter when you use free_symbols:

>>> T = Tuple(*sols)
>>> p = T.free_symbols
>>> T.subs(p[0],1)
(-2, -3)
jakoblem commented 2 years ago

Thanks, free_symbols may work for me, but I wish there was a simpler solution. I am using SymPy for (university) teaching for students without programming background. Students often wants to substitute values of the solution variables, and the current way to do this requires several steps (and may depend on the output type of the solver, e.g., diophantine, solve, linsolve, solveset)

sylee957 commented 2 years ago

We may need some research about the types of output that solvers. For describing the infinite set of solutions, there are many options, from using the substitution form (like first order logic) or explicitly giving the basis (like linear algebra). There are also the cases where algebraic equations cannot be transformed to the variable to term substitution form, but another simpler algebraic equation is returned instead.

oscarbenjamin commented 2 years ago

See #20682 for some suggestions for improving the diophantine API.