问题描述
我对 sympy 还很陌生.我试图用 linsolve() 求解一个线性方程组.这产生了一个可以用以下两行重现的解决方案.
d = 符号(d")解决方案 = sets.FiniteSet((d + 1, -d + 4, -d + 5, d))
我的解决方案遵守限制,即所有四个值都必须是正整数.这发生在 d = 0, 1, 2, 3, 4.
我能够在固定的 d(例如 d = 0)下评估解决方案
solution.subs({d : 0})
我希望自动将解决方案集限制为有效的解决方案.在数学上,这相当于与 \mathbb{N^0}^4 的交集.在实践中,我想得到一个来自
的输出 for d_fixed in range(5):solution.subs({d : d_fixed})
我.e.
{(1, 4, 5, 0)}{(2, 3, 4, 1)}{(3, 2, 3, 2)}{(4, 1, 2, 3)}{(5, 0, 1, 4)}
我该怎么做?
我认为按照这些思路可以做到这一点,只要你多施一点魔法即可.
>>>从 sympy 导入 *>>>var('d')d>>>解决方案 = sets.FiniteSet((d+1,-d+4,-d+5,d))>>>列表(列表(解决方案)[0])[d + 1, -d + 4, -d + 5, d]>>>从 sympy.solvers.inequalities 导入 reduce_inequalities>>>reduce_inequalities([0感谢 https://stackoverflow.com/users/1879010/dietrich 发表评论直到看到你的问题才忘记阅读.
I am fairly new to sympy. I tried to solve a system of linear equations with linsolve(). This yields a solution which can be reproduced with the two following lines.
d = symbols("d")
solution = sets.FiniteSet((d + 1, -d + 4, -d + 5, d))
My solution obeys the restriction, that all four values must be positive integers. This happens for d = 0, 1, 2, 3, 4.
I was able to evaluate solution at a fixed d (e. g. d = 0) with
solution.subs({d : 0})
What I would like to have restrict the set of solutions to the valid ones automatically. Mathematically that amounts to the intersection with \mathbb{N^0}^4. In practice I would like to get an output like from
for d_fixed in range(5):
solution.subs({d : d_fixed})
i. e.
{(1, 4, 5, 0)}
{(2, 3, 4, 1)}
{(3, 2, 3, 2)}
{(4, 1, 2, 3)}
{(5, 0, 1, 4)}
How can I do this?
I think something along these lines will do it, with a little extra magic from you.
>>> from sympy import *
>>> var('d')
d
>>> solution = sets.FiniteSet((d+1,-d+4,-d+5,d))
>>> list(list(solution)[0])
[d + 1, -d + 4, -d + 5, d]
>>> from sympy.solvers.inequalities import reduce_inequalities
>>> reduce_inequalities([0<=d + 1, 0<=-d + 4, 0<=-d + 5, 0<=d],[d])
And(0 <= d, d <= 4)
I am indebted to https://stackoverflow.com/users/1879010/dietrich for a comment that I have been forgetting to read until I saw your question.
这篇关于如何限制包含符号的 sympy FiniteSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!