SymPy - 任意数量的符号 [英] SymPy - Arbitrary number of Symbols

查看:36
本文介绍了SymPy - 任意数量的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个函数来求解任意数量的联立方程.方程的数量由函数的参数之一设置,每个方程由许多符号构建 - 与方程的符号一样多.这意味着我不能简单地对方程进行硬编码,甚至不能对将方程组合在一起所需的符号进行硬编码;该函数需要能够处理任意数量的方程.所以,我的问题是,如何生成符号列表?

I am coding a function that solves an arbitrary number of simultaneous equations. The number of equations is set by one of the parameters of the function and each equation is built from a number of symbols - as many symbols as there are equations. This means that I can't simply hardcode the equations, or even the symbols needed to put together the equations; the function needs to be able to handle any number of equations. So, my question is, how do I produce a list of symbols?

我有一个可能的解决方案,但我的直觉告诉我它不会非常有效.请让我知道是否有更好的方法来做到这一点.

I have one possible solution, but my gut tells me that it's not going to be very efficient. Please let me know if there is a better way of doing this.

我是 SymPy 的新手,我仍然在摸索.据我所知,符号需要用字符串定义.因此,我可以通过将一个递增的数字附加到一个字母(比如t0"、t1"等)来生成一系列字符串,将它们添加到列表中,然后使用这些字符串作为参数创建符号.这些符号本身将存储在一个列表中,并用于生成方程.

I'm new to SymPy and am still feeling my way about. As far as I can see, Symbols need to be defined with a string. Therefore, I can produce a series strings via appending an incrementing number to a letter (say 't0', 't1', etc), add them to a list and then create the symbols using those strings as parameters. Those symbols would themselves be stored in a list and would be used to produce the equations.

def solveEquations(numEquations):
    symbolNameList = []
    symbolList = []
    equationList = []
    for i in range(numEquations):
        name = 't' + str(i)
        symbolNameList.append(name)
        symbolList.append(Symbol(name))

    for i in range(numEquations):
        equation = 0
        for sym in symbolList:
            equation += sym ** i # Or whatever structure the equation needs
        equationList.append(equation)


    #Then go on to solve the equations...

这是最好的方法,还是有更有效的方法?

Is this the best way of doing this, or is there a more efficient approach?

推荐答案

symbols 函数可用于轻松生成符号列表

The symbols function can be used to easily generate lists of symbols

In [1]: symbols('a0:3')
Out[1]: (a₀, a₁, a₂)

In [2]: numEquations = 15

In [3]: symbols('a0:%d'%numEquations)
Out[3]: (a₀, a₁, a₂, a₃, a₄, a₅, a₆, a₇, a₈, a₉, a₁₀, a₁₁, a₁₂, a₁₃, a₁₄)

这篇关于SymPy - 任意数量的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆