简体   繁体   中英

How to generate symbolic variables in a for loop using Sympy (Python)

Depending on the input of my tool I need multiple variables: A_n , B_n , C_n and D_n for n (integer) in range [1, x] to formulate x equation of the following form:

W(z) = A_n*cosh(beta*z) + B_n*sinh(beta*z) + C_n*cos(beta*z) + D_n*sin(beta*z)

I'm using Sympy, and I cannot find a way to replace n for the integer in range [1, x] and use that symbol ( A1 , A2 , B1 , B2 , etc.) in a loop (to generate the symbol or for further calculations.

How can I write or call these variables conveniently in a for loop, such that I don't have to write it by hand?

You could use functions with integer arguments to represent your constants or indexed variables. Here is a toy example:

>>> A,B,C = symbols('A:C', cls=Function)
>>> eq = A(i)*x + B(i)*y + C(i)
>>> [eq.subs(i,j) for j in range(2)]
[x*A(0) + y*B(0) + C(0), x*A(1) + y*B(1) + C(1)]

Those functions can be replaced with values when you known them.

Instead of using these functions you could used Indexed, too:

>>> Ai=Indexed('A',i)
>>> Ai
A[i]
>>> _.subs(i,0)
A[0]

Example of creating sympy variables/symbols with a for loop

I just came up against this problem (sorry my answer didn't come sooner) and after an hour of trying things this is what I came out to. I have imported sympy as sm by the way. I use the globals argument to convert the strings into legal variable names, and then I can make strings with the right indices by forcing i and j to become strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM