问题描述
我正在尝试在python中求解非线性方程。我已经尝试过使用Sympy的求解器,但是它似乎无法在for循环语句中使用。我想解决输入[N] 范围内的变量x 。
我在下面附加了我的代码
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
f_curve_coefficients = [-7.14285714e-02,1.96333333e+01,6.85130952e+03]
S = [0.2122,0]
a2 = f_curve_coefficients[0]
a1 = f_curve_coefficients[1]
a0 = f_curve_coefficients[2]
s2 = S[0]
s1 = S[1]
s0 = S[2]
answer=[]
x = symbols('x')
for N in range(0,2500,5):
solve([a2*x**2+a1*N*x+a0*N**2-s2*x**2-s1*x-s0-0])
answer.append(x)
print(answer)
解决此问题的方法可能比使用sympy更为有效*任何帮助将不胜感激。
注意,从Matlab转换后,我还是python的新手。我可以在Matlab中轻松解决此问题并可以附加代码,但是我在Python中对此感到困惑
解决方法
回答您的问题“解决此问题的方法可能比使用sympy *更有效的方法”
您可以使用fsolve查找非线性方程的根: 在给定初始估计的情况下,fsolve返回由func(x)= 0定义的(非线性)方程的根 https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html
下面是代码:
from scipy.optimize import fsolve
import numpy as np
def f(variables) :
(x,y) = variables
first_eq = 2*x + y - 1
second_eq = x**2 + y**2 - 1
return [first_eq,second_eq]
roots = fsolve(f,(-1,-1)) # fsolve(equations,X_0)
print(roots)
# [ 0.8 -0.6]
print(np.isclose(f(roots),[0.0,0.0])) # func(root) should be almost 0.0.
如果您希望使用sympy,则可以使用nsolve。
>>> nsolve([x+y**2-4,exp(x)+x*y-3],[x,y],[1,1])
[0.620344523485226] [1.83838393066159]
第一个参数是方程式列表,第二个参数是变量列表,第三个参数是初始猜测。
另外,有关详细信息,您可以查看先前在堆栈溢出中询问的有关在python中解决非线性方程式的方法的类似问题: How to solve a pair of nonlinear equations using Python?
,根据this documentation,solve
的输出就是解决方案。没有为x
分配任何内容,仍然只是符号。
x = symbols('x')
for N in range(0,2500,5):
result = solve(a2*x**2+a1*N*x+a0*N**2-s2*x**2-s1*x-s0-0)
answer.append(result)