如何用sympy声明自然符号?(How can I declare natural symbols with sympy?)

我知道如何声明整数符号:

from sympy import symbols a, b, c, m, n = symbols('a b c m n', Integer=True)

但是我想这些符号是没有零的自然数(严格为正整数)。 我该怎么做? 谢谢

编辑:

如果我计算丢番图方程,它也给了我负面的解决方案,我只想要积极的解决方案:

from sympy.solvers.diophantine import diophantine from sympy import symbols a, b, c, m, n = symbols('a b c m n', integer=True, positive=True) a = n ** 2 - m ** 2 b = 2 * n * m c = n ** 2 + m ** 2 diof = diophantine(n ** 2 + m * n - 500) print(diof)

看:{(121,4),(499,-500),(95,-100),(499,1),( - 40,-10),(40,-50),( - 499,500) ,( - 95,-5),( - 40,50),( - 95,100),(5,20),( - 5,25),( - 248,250),( - 499,-1) ,(121,-125),(5,-25),( - 121,125),( - 5, - 20),( - 121,-4),(248,-250),(95,5) ,(-248,-2),(40,10),(248,2)}

I know how to declare integer symbols:

from sympy import symbols a, b, c, m, n = symbols('a b c m n', Integer=True)

But I want that symbols are natural numbers without zero (strictly positive integers). How can I do it? Thanks

Edit:

If I calculate diophantine equation, it gives me negative solutions too, and i want only positive solutions:

from sympy.solvers.diophantine import diophantine from sympy import symbols a, b, c, m, n = symbols('a b c m n', integer=True, positive=True) a = n ** 2 - m ** 2 b = 2 * n * m c = n ** 2 + m ** 2 diof = diophantine(n ** 2 + m * n - 500) print(diof)

Look: {(121, 4), (499, -500), (95, -100), (499, 1), (-40, -10), (40, -50), (-499, 500), (-95, -5), (-40, 50), (-95, 100), (5, 20), (-5, 25), (-248, 250), (-499, -1), (121, -125), (5, -25), (-121, 125), (-5, -20), (-121, -4), (248, -250), (95, 5), (-248, -2), (40, 10), (248, 2)}

最满意答案

我已经打开了https://github.com/sympy/sympy/issues/7444 。 与此同时,您可以按照老式的方式过滤解决方案。

>>> {(i, j) for i, j in diof if i > 0 and j > 0} set([(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)])

I've opened https://github.com/sympy/sympy/issues/7444 about this. In the mean time, you can just filter the solutions the old fashioned way.

>>> {(i, j) for i, j in diof if i > 0 and j > 0} set([(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)])

更多推荐