简体   繁体   English

如何使用 Sympy (Python) 在 for 循环中生成符号变量

[英]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:根据我工具的输入,我需要多个变量: A_nB_nC_nD_n用于[1, x]范围内的n (整数),以制定以下形式的x方程:

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.我正在使用 Sympy,但我找不到在[1, x]范围内为 integer 替换n并在循环中使用该符号( A1A2B1B2等)的方法(生成符号或用于进一步计算。

How can I write or call these variables conveniently in a for loop, such that I don't have to write it by hand?如何在 for 循环中方便地编写或调用这些变量,这样我就不必手动编写了?

You could use functions with integer arguments to represent your constants or indexed variables.您可以使用带有 integer arguments 的函数来表示您的常量或索引变量。 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:除了使用这些函数,您也可以使用 Indexed:

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

Example of creating sympy variables/symbols with a for loop使用 for 循环创建 sympy 变量/符号的示例

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.顺便说一下,我已经将 sympy 导入为sm 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.我使用 globals 参数将字符串转换为合法的变量名,然后我可以通过强制 i 和 j 成为字符串来创建具有正确索引的字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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