【问题标题】:sympy: how to save solution from "solve" for reuse?sympy:如何从“解决”中保存解决方案以供重用?
【发布时间】:2014-01-27 00:15:29
【问题描述】:

我正在使用带有 sympy 0.7.4.1 的 python3。我不知道如何保存解决方案以备将来使用(我在手册或谷歌上找不到任何有用的东西)。例如,我有一些方程 eq1,eq2 和 t1+t2+t3==0,那么我可以通过以下方式求解方程

solve([t1+t2+t3,eq1,eq2],[t1,t2,t3]

但我想将解决方案存储到 t1,t2,t3,以便我可以将它们用于其他操作。有没有一种简单的方法可以实现这一目标?简单地使用 [t1,t2,t3]=solve([t1+t2+t3,eq1,eq2],[t1,t2,t3] 不起作用。

solve的返回是

{t2: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, t3: 3*theta_2**2/4 - 3*theta_2*theta_3/2 + 3*theta_3**2/4, t1: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8}

如果我添加标志 set=True,那就是

([t1, t2, t3], {(-3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, 3*theta_2**2/4 - 3*theta_2*theta_3/2 + 3*theta_3**2/4)})

对于dict=True,是

[{t2: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8, t3: 3*theta_2**2/4 - 3*theta_2*theta_3/2 + 3*theta_3**2/4, t1: -3*theta_2**2/8 + 3*theta_2*theta_3/4 - 3*theta_3**2/8}]

【问题讨论】:

  • 如果您显示 solve() 返回的内容会有所帮助。它应该是一个数组或字典。

标签: python sympy


【解决方案1】:

首先请注意,一般来说,您可以有多种解决方案。这就是为什么 set=True 返回一组元组(而不仅仅是一个元组),而 dict=True 返回一个字典列表(而不仅仅是一个)。

最简单的是dict=True。要访问解决方案,请执行以下操作

sols = solve([t1 + t2 + t3, eq1, eq2], [t1, t2, t3])
sols[0][t1] # This is t1 in the first solution 

如果有更多解决方案,它们将是sols[1]sols[2],等等。在每种情况下,字典中的键都是该解决方案所对应的符号,例如 t1t2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 2019-04-24
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多