First time here? Check out the FAQ!

Ask Your Question
2

Infinitely many variables

asked 3 years ago

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:

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?

Preview: (hide)

2 Answers

Sort by » oldest newest most voted
2

answered 3 years ago

tmonteil gravatar image

updated 3 years ago

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

answered 3 years ago

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
        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
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

1 follower

Stats

Asked: 3 years ago

Seen: 344 times

Last updated: Feb 03 '22