Ask Your Question

Infinitely many variables

asked 2022-02-02 21:41:45 +0200

mrutkuokur gravatar image

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:

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 flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2022-02-02 22:38:41 +0200

tmonteil gravatar image

updated 2022-02-02 22:40:34 +0200

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)

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)
edit flag offensive delete link more

answered 2022-02-03 13:27:30 +0200

rburing gravatar image

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
            raise KeyError(key)


sage: x = keydefaultdict(lambda i: SR.var('x_{}'.format(i)))
sage: x[1]
sage: x[12]
edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools

1 follower


Asked: 2022-02-02 21:41:45 +0200

Seen: 44 times

Last updated: Feb 03