我在 python 中做了这个小测试程序,看看 solve
和 nsolve
是如何工作的。
from sympy import *
theta = Symbol('theta')
phi = Symbol('phi')
def F(theta,phi):
return sin(theta)*cos(phi)+cos(phi)**2
def G(phi):
return ((1 + sqrt(3))*sin(phi) - 4*pi*sin(2*phi)*cos(2*phi))
solution1 = solve(F(pi/2,phi),phi)
solution2 = solve(G(phi),phi)
solution3 = nsolve(G(phi),0)
solution4 = nsolve(G(phi),1)
solution5 = nsolve(G(phi),2)
solution6 = nsolve(G(phi),3)
print solution1, solution2, solution3, solution4, solution5, solution6
我得到这个输出:
[pi/2, pi] [] 0.0 -0.713274788952698 2.27148961717279 3.14159265358979
solve的第一次调用给了我对应函数的两个解。但不是第二个。我想知道为什么? nsolve
似乎适用于初始测试值,但根据该值,它会给出不同的数值解。有没有一种方法可以在一行中使用 nsolve
或其他函数获取所有数值解的列表?
最佳答案
The first call of solve gave me two solutions of the corresponding function. But not the second one. I wonder why?
一般来说,您不能以符号方式求解方程,显然 solve
正是这样做的。换句话说:如果 solve
可以解出你的方程,那你就幸运了,典型的技术应用没有解析解,也就是说,不能用符号求解。
因此后备选项是从初始点开始数值求解方程。在一般情况下,即使存在解决方案,也不能保证 nsolve
会找到解决方案。
Is there a way to get the list all numerical solutions with nsolve or with another function, in just one line?
一般来说,不会。不过,您可以从一些初始猜测开始nsolve
并跟踪找到的解决方案。您可能希望在感兴趣的区间内均匀分布您的初始猜测。这称为多启动法。
关于python - Sympy nsolve 函数和多个解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13344471/