# Defining family of multivariable polynomials

Brand new to Sage here and trying to define a family of polynomials indexed by natural numbers. In particular, I'd like to be able to generate then perform symbolic calculations with the family of polynomials defined for all $n\in \mathbb{N}$ and all $k=0,\dotsc, 2n$ by $$p_{n,k}=\begin{cases} 0 & \textrm{if } k=0\newline \sum_{j=1}^k x_j&\textrm{if } k\leq n\newline \sum_{j=1}^{2n-k+1}x_j&\textrm{if }k>n \end{cases}$$

So far the attempts that I've had are of the form:

sage: h = lambda k:sum([var('d_%d' %(i+1)) for i in range(k)])


but I don't seem to easily perform calculations with these. Another method I was trying is defining $\mathbb{Q}[x_0,\dotsc, x_n]$ then trying to define these polynomials using conditional statements. I seem to keep getting errors stating my variables don't exist.

Would love some help or a hint.

edit retag close merge delete

Your $p_k$ silently depends on $n$. So you want to fix $n$ and study the $p_k$?

As you write them, your $p_k$ are first-degrees polynomials of $n$ variables at most. Is that really what you want ?

That is correct, I'd like to fix any $n$ then study the $p_k$.

Yes, these will be degree $1$ polynomials in at most $n$ variables.

• it might make sense to call the polynomials $p_{n, k}$.
• in the case $0 < k \le n$, the formula should have $x_j$, not $x_k$
• indenting the code line h = lambda k: ... by 4 spaces will make it display as code

Thanks for taking all the comments into account and editing your question!

Sort by » oldest newest most voted

Sage has a constructor for polynomial rings in countably many variables.

Using this constructor, the polynomials $p_{n, k}$ in the question can be defined as follows.

Define the polynomial ring $\mathbb{Q}[x_0, x_1, x_2, ...]$:

sage: R.<x> = InfinitePolynomialRing(QQ)


Now x[j] gives $x_j$.

sage: x
x_2
sage: x
x_9876


Define a function p such that p(n, k) gives $p_{n, k}$:

def p(n, k):
if n not in NN or k not in NN or k > 2*n:
raise ValueError("Unsupported values: n = {}, k = {}".format(n, k))
if k == 0:
return R.zero()
if 1 <= k <= n:
return sum(x[j] for j in (1 .. k))
# case n < k <= 2* n:
return sum(x[j] for j in (1 .. 2*n-k+1))


Now p(n, k) returns $p_{n, k}$:

sage: p(4, 3)
x_3 + x_2 + x_1
sage: p(4, 7)
x_2 + x_1
sage: p(4, 3) + p(4, 7)
x_3 + 2*x_2 + 2*x_1

more