'How to define a lot of symbols in SymPy
I am trying to define a lot of variables in "sympy" for symbolic processing.
import sympy as sp
b_0 = sp.symbols('b_0')
b_1 = sp.symbols('b_1')
...
b_X = sp.symbols('b_X')
and so on with the X
going from 1 to 1000.
Is there an easy way to do it?
Solution 1:[1]
There are a few options:
>>> sp.symbols('b_0:10')
(b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9)
or, using a formatted string,
>>> n = 10
>>> sp.symbols('b_0:{}'.format(n))
(b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9)
These return a tuple of symbols. There are more formatting options: see symbols
docs.
There is also a function to generate a NumPy array of symbols:
>>> sp.symarray('b', 10)
array([b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9], dtype=object)
All of these examples are meant to be assigned to something. For example, b = sp.symbols('b_0:10')
assigns the tuple of symbols to b, so they can be accessed as b[0], b[1]
, etc. SymPy symbols are not accessed by the string representing them, such as "b_0" or "b_1"
.
Finally, there are Indexed objects in case you need an array of symbols of undetermined size: Indexed objects are created on the fly as you use A[n]
notation with A
being an IndexedBase.
Solution 2:[2]
If you want to still be able to call individuals symbols, like b_0
:
Since:
from sympy import symbols
# Number of symbols you need
X = 5
b = symbols(f"b_0:{X}")
>>> b
(b_0, b_1, b_2, b_3, b_4)
>>> b_0
NameError: name 'b_0' is not defined
You could add them to the local variables through a dictionary:
from sympy import symbols
# Number of symbols you need
X = 5
# To still have b[i]
b = symbols(f"b_0:{X}")
b_dict = {f"b_{i}": b[i] for i in range(X)}
locals().update(b_dict)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Owen |