如何使用 sympy 在 Python 中求解联立方程 [英] How can I solve a simultaneous equation in Python using sympy

查看:36
本文介绍了如何使用 sympy 在 Python 中求解联立方程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个等式:

40 = Vmax*5.041667 + (Vmax**2/Amax)*sympy.exp((-Amax/Vmax)*5.041667) - (Vmax**2/Amax)
20 = Vmax*2.897628 + (Vmax**2/Amax)*sympy.exp((-Amax/Vmax)*2.897628) - (Vmax**2/Amax)   

我在 sympy 中编写了以下代码来求解这个联立方程来求解 Vmax 和 Amax

I wrote the following codes in sympy to solve this simultaneous equation to solve for Vmax and Amax

import sympy as sp
Vmax, Amax = symbols('Vmax, Amax')

eq1 = Vmax*5.041667 + (Vmax**2/Amax)*sympy.exp((-Amax/Vmax)*5.041667) - (Vmax**2/Amax)
eq2 = Vmax*2.897628 + (Vmax**2/Amax)*sympy.exp((-Amax/Vmax)*2.897628) - (Vmax**2/Amax)         

print(nsolve((eq1, eq2), (Vmax, Amax), (40,20)))

这段代码给出了错误的答案.而我认为正确的以下代码需要很长时间来计算.

This code gives the wrong answer. And the following code which I think is right takes too long to compute.

from sympy import *
Vmax, Amax = symbols('Vmax, Amax')
eq1 = Vmax*5.041667 + (Vmax**2/Amax)*sympy.exp((-Amax/Vmax)*5.041667) - (Vmax**2/Amax)
eq2 = Vmax*2.897628 + (Vmax**2/Amax)*sympy.exp((-Amax/Vmax)*2.897628) - (Vmax**2/Amax)
solve([eq1-40, eq2-20], (Vmax, Amax))

知道我可以做些什么来修复我的代码以便我能得到正确的答案吗?

Any idea what I can do to fix my code so I can get the right answer?

推荐答案

您误解了 nsolve 的工作原理.第三个参数是用于启动寻根算法的初始猜测.这里 [1, 1] 可以正常工作:

You've misunderstood how nsolve works. The third argument is an initial guess that is used to start the root-finding algorithm. Here [1, 1] will work fine as the guess:

In [26]: from sympy import symbols, Eq, nsolve, exp                                                                                                            

In [27]: Vmax, Amax = symbols('Vmax, Amax')                                                                                       

In [28]: eq1 = Eq(Vmax*5.041667 + (Vmax**2/Amax)*exp((-Amax/Vmax)*5.041667) - (Vmax**2/Amax), 40) 
    ...: eq2 = Eq(Vmax*2.897628 + (Vmax**2/Amax)*exp((-Amax/Vmax)*2.897628) - (Vmax**2/Amax), 20)                           

In [29]: nsolve([eq1, eq2], [Amax, Vmax], [1, 1])                                                                                 
Out[29]: 
⎡11.8641453843429⎤
⎢                ⎥
⎣9.41244210257784⎦

请注意,这只能从任何特定的初始猜测开始找到一个解决方案.像这样的系统可能有不止一种解决方案.

Note that this only finds one solution starting from any particular initial guess. It is possible that that a system like this has more than one solution.

这篇关于如何使用 sympy 在 Python 中求解联立方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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