假设我定义了两个符号xy

import sympy as sp

x = sp.symbols('x', integer=True)
y = sp.symbols('y', integer=True)


我知道我可以这样用一个变量求解方程:

expr = 3*x**2 - 12

result = sp.solve(expr, x)
print(result)



  [-2,2]


我可以限制解决方案范围

result = sp.solve([expr, x>0], x)
print(result)



  等式(x,2)


现在,我想用(0, 10)范围内的两个未知数求解方程。这是我尝试过的:

expr = 3*x - y - 10
result = sp.solve([expr, x>0, x<10, y>0, y<10], x, y)


但是它给出了NotImplementedError

NotImplementedError:
inequality has more than one symbol of interest.


确实没有执行,还是我做错了什么?我知道sympy是一个功能强大的库,因此我希望sympy可以解决此类问题。我期望的是以下解决方案:

(x=4, y=2), (x=5, y=5), (x=6, y=8)

互联网上的人们建议使用solvesetnonlinsolvelinsolve,但我也无法使其与这些方法一起使用。

最佳答案

solve中使用不等式经常会使用户感到困惑。我认为大多数用户都希望使用不等式来过滤您所说的解决方案。但是solve实际上希望使用不等式简化不等式的单变量系统,这是完全不同的东西,例如:

In [3]: solve([x**2+1<10, x>2])
Out[3]: 2 < x ∧ x < 3


请注意,此处的Solve返回的是Boolean结果,而不是通常返回的Expr列表。我认为,由于这种交替使用solve函数结合方程式和不等式的方法,并不能完全满足用户的期望。为了说明为什么这很有用,我实际上使用了下面的solve

您的示例确实是一个飞马问题,因为方程组尚未确定(两个未知数中有1个方程),但您只需要整数解。我以前从未使用过双色子求解器,但我只是尝试了一下:

from sympy import *

x, y = symbols('x, y', integer=True)

eq = 3*x - y - 10
conds = [(0 < x), (x < 10), (0 < y), (y < 10)]

# Solve the diophantine equation for solutions in parameter t_0
t, t_0 = symbols('t, t_0', integer=True)
gensol = diophantine(eq, t, [x, y])
((xs, ys),) = gensol

# "Solve" the inequalities for constraints on t_0
conds_t = [cond.subs(x, xs).subs(y, ys) for cond in conds]
conds_t_sol = solve(conds_t, t_0)

# Find the finite set of values for t_0 and sub in to general solution
set_t0 = (conds_t_sol.as_set() & Integers)
sol_set = [(xs.subs(t_0, ti), ys.subs(t_0, ti)) for ti in set_t0]

print(sol_set)


输出是

[(4, 2), (5, 5), (6, 8)]

09-10 02:48
查看更多