# referencing polynomial variables

Suppose I have a polynomial $f$ in the variables $x_1, \dots, x_5$ defined by something like

f = 0
for counter in range(1,5):
f += mylist[counter] * var('x' + str(counter))


where mylist is some list of integers. Then I can evaluate $f$ by e.g.

f.subs(x1=1,x2=2,x3=3,x4=4,x5=5)


Question: How do I do this evaluation when $f$ is in $n>>0$ variables?

I want to write something like

for counter in range(1,n):
f = f.subs(var('x' + str(counter))=counter)


but this isn't a valid argument for subs. This must be some way to coerce this to work.

edit retag close merge delete

Sort by ยป oldest newest most voted

Note that it is also possible to do this in a genuine Polynomial Ring, instead of the (sometimes weird) Symbolic Ring:

sage: mylist = [1,4,2,3,6,12,21,6,2]
sage: n = len(mylist)
sage: R = PolynomialRing(ZZ, n, 'x'); R
Multivariate Polynomial Ring in x0, x1, x2, x3, x4, x5, x6, x7, x8 over Integer Ring
sage: P = sum(c*R.gen(i) for i, c in enumerate(mylist)); P
x0 + 4*x1 + 2*x2 + 3*x3 + 6*x4 + 12*x5 + 21*x6 + 6*x7 + 2*x8
sage: P(range(n))
285

more

2

It is worth mentioning that R = PolynomialRing(ZZ, n, 'x') and P = sum(c\*R.gen(i) for i, c in enumerate(mylist)) are perhaps a little less cryptic, and that R.inject_variables() allows one to write things like Q = 3\*x1\*x2^3 - x3^4

( 2013-05-27 06:39:45 -0500 )edit

Thanks for your suggestion, this indeed less hackish, i updated my answer accordingly.

( 2013-05-28 03:36:07 -0500 )edit

The simplest solution is just to use dictionary arguments for subs.

for counter in range(1,n):
f = f.subs(var('x' + str(counter))=counter)


which throws a SyntaxError, you can write

for counter in range(1,n):
f = f.subs({var('x' + str(counter)):counter})

more

A possible approach might be the following:

vars=[]
f = 0
for counter in range(1,5):
vars.append( var('x'+str(counter) ))
f += mylist[counter] * vars[counter]


Then you can use a dictionary to evaluate. Say you have n variables and want vars[i] to take value val[i] where val is a list of values. So first construct a dictionary with

eval_dict = dict( [ (vars[i], val[i]) for i in range(n) ] )


Then you can evaluate by executing

f( eval_dict )

more