# Infinitely many variables

Is there a way to define infinitely many variables? At the moment, I am able to define arbitrarily big number of symbolic variables, x[i], using a code as follows:

N=3
x=np.zeros(shape=(N),dtype=object)
for i in range(N):
x[i]=var('x_', n=N )[i]


I would like to be able to define x_i for i=1,2,... Is this possible using the symbolic ring?

edit retag close merge delete

Sort by ยป oldest newest most voted

You can not create infinitely many symbols (a.k.a. symbolic variables) in the sense that they will fill up your memory, but you can create as many such symbols on demand (lazily). As a quick example, you can define the following function:

sage: def x(i):
....:     return SR.var('x_{}'.format(i))


Then, you can do things like:

sage: x(4)
x_4

sage: x(4) + x(7)^2
x_7^2 + x_4

sage: sum(x(i)^i for i in range(10))
x_9^9 + x_8^8 + x_7^7 + x_6^6 + x_5^5 + x_4^4 + x_3^3 + x_2^2 + x_1 + 1


Note that if you reuse twice the same symbol, it is not recreated:

sage: x(2) is x(2)
True

more

In case you prefer indexing syntax x[i] over function call syntax x(i), you can use the following helper class:

from collections import defaultdict

class keydefaultdict(defaultdict):
def __missing__(self, key):
if self.default_factory is not None:
ret = self[key] = self.default_factory(key)
return ret
else:
raise KeyError(key)


Then:

sage: x = keydefaultdict(lambda i: SR.var('x_{}'.format(i)))
sage: x[1]
x_1
sage: x[12]
x_12

more