Processing math: 100%
Ask Your Question
0

referencing polynomial variables

asked 11 years ago

OliverP gravatar image

Suppose I have a polynomial f in the variables x1,,x5 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.

Preview: (hide)

3 Answers

Sort by » oldest newest most voted
2

answered 11 years ago

tmonteil gravatar image

updated 11 years ago

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
Preview: (hide)
link

Comments

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

Francis Clarke gravatar imageFrancis Clarke ( 11 years ago )

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

tmonteil gravatar imagetmonteil ( 11 years ago )
0

answered 11 years ago

fidbc gravatar image

updated 11 years ago

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 )
Preview: (hide)
link
0

answered 11 years ago

OliverP gravatar image

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

Instead of

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})
Preview: (hide)
link

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 11 years ago

Seen: 485 times

Last updated: May 28 '13