Creating an array of variables

Here is a very very basic question.

I want to create a polynomial, say a_0x^0 + a_1x + a_2*x^2+ \cdots + a_{20} x^{20}.

I could define these a_i one at a time, but it would be much better to have a way to create an array A of length 20 where A[i] is the coefficient a_i. The idea is that I want to do some operations and solve for these coefficients, which will end up being rational numbers.

There must be some very basic command that I don't know, but I can't find it in the documentation.

edit retag close merge delete

Sort by » oldest newest most voted I don't know that there's a command in particular to construct a polynomial with symbolic coefficients, but here's what I'd do:

sage: N = 20
sage: x = var("x")
sage: aa = list(var('a_%d' % i) for i in (0..N))
sage: p = sum(a*x**i for i,a in enumerate(aa))
sage: p
a_20*x^20 + a_19*x^19 + a_18*x^18 + a_17*x^17 + a_16*x^16 + a_15*x^15 + a_14*x^14 + a_13*x^13 + a_12*x^12 + a_11*x^11 + a_10*x^10 + a_9*x^9 + a_8*x^8 + a_7*x^7 + a_6*x^6 + a_5*x^5 + a_4*x^4 + a_3*x^3 + a_2*x^2 + a_1*x + a_0

It's easy enough to change where x and the coefficients a are living (right now they're in the Symbolic Ring) if needed.

more

Why does one need the list? Can't one just do: sum([var(join(['a',str(i)],sep=''))*x^i for i in (0..N)])

@Xaver: sure, but then it's much less convenient to refer to the variables by themselves later. If you store them in a list or a dict or something, then you can write aa and get the variable a_10.

@DSM: for sage: p=sum([var(join(['a',str(i)],sep=''))*x^i for i in (0..N)]), couldn't you still use p.operands()[N-10].operands() and get a10, so you can still address them in a list fashion ... but I agree this now looks ugly (and with karma 51 I'd better shut up ;) )

@Xaver: I think it's worse than that, as what if you add new operands to p (or zero a term)? Then you've got no guarantee that the ith operand is a_i. So you have to keep a copy of the original p around just in case, in which case it's simpler to keep the variables around. But pay no attention to karma, lots of main devels around here have only middling karma. :^)

You could use the method shown here: http://groups.google.com/group/sage-s...

See, for example: http://sagenb.org/home/pub/3352/

class VariableGenerator(object):
def __init__(self, prefix):
self.__prefix = prefix
@cached_method
def __getitem__(self, key):
return SR.var("%s%s"%(self.__prefix,key))

a=VariableGenerator('a')
p = sum(a[i]*x**i for i in range(10))
more

@Jason Grout: should something like your recipe be made canonical [i.e. added to the Sage stdlib]? Overriding __getitem__ -- and remembering to cache the method so that a is a -- is a little beyond what beginners should need to understand to get the outcome, IMHO.

I've been hoping someone will make a patch and shepherd it through the review process!