在同情中将字符串声明为“常量”

时间:2022-06-02 20:23:40

I'm trying to implement an algorithm which involves polynomials in two variables "x" and "y", but some times I need to interpret them as univariable polynomials (that is, leaving x as a constant), for example, in order use the function gcdex (the extended euclidean algorithm). Is there a simple way to make sympy interpret "x" as a constant instead of a variable?

我正在尝试实现一个算法,该算法涉及两个变量“x”和“y”中的多项式,但有时我需要将它们解释为单变量多项式(即,将x保持为常数),例如,为了使用函数gcdex(扩展的欧几里德算法)。是否有一种简单的方法可以将“x”解释为常数而不是变量?

I've tried the following:

我尝试过以下方法:

import sympy

x = sympy.Symbol('x', constant=True)
y = sympy.Symbol('y')
f = sympy.Poly(x*y + y**2)
g = sympy.Poly(x+y)
(s, t, gcd) = sympy.gcdex(f,g)

but it throws an error: univariate polynomials expected.

但它会引发错误:预期的单变量多项式。

1 个解决方案

#1


2  

The way to do this is to specify the generators of the polynomials when you create them. For instance, to treat only y as a variable, use

执行此操作的方法是在创建多项式时指定它们的生成器。例如,要仅将y视为变量,请使用

f = Poly(x*y + y**2, y)

By default, Poly assumes that all the symbols in an expression should be generators.

默认情况下,Poly假定表达式中的所有符号都应该是生成器。

You can also pass the generator as the third argument to gcdex

您还可以将生成器作为第三个参数传递给gcdex

s, t, gcd = gcdex(f, g, y)

gives

(s, t, gcd) == (Poly(0, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'), Poly(x + y, x, y, domain='ZZ'))

#1


2  

The way to do this is to specify the generators of the polynomials when you create them. For instance, to treat only y as a variable, use

执行此操作的方法是在创建多项式时指定它们的生成器。例如,要仅将y视为变量,请使用

f = Poly(x*y + y**2, y)

By default, Poly assumes that all the symbols in an expression should be generators.

默认情况下,Poly假定表达式中的所有符号都应该是生成器。

You can also pass the generator as the third argument to gcdex

您还可以将生成器作为第三个参数传递给gcdex

s, t, gcd = gcdex(f, g, y)

gives

(s, t, gcd) == (Poly(0, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)'), Poly(x + y, x, y, domain='ZZ'))