我正在尝试在for循环中使用 fsolve 解决一个(非线性)方程,但是在我的代码中似乎不起作用。
在How to solve nonlinear equations using a for loop in python? 的帮助下,我设法解决了两个或多个方程,但不能使它适用于单个非线性方程。
* 请注意,N是我们替换为使用for循环的步进范围值
from scipy.optimize import fsolve
import numpy as np
f_curve_coefficients = [-7.14285714e-02, 1.96333333e+01, 6.85130952e+03]
S = [0.2122, 0, 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]
def f(variable):
x = variable
first_eq =a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)
return [first_eq]
for N in range(1,6,1):
roots = fsolve(f,20) # fsolve(equations, X_0)
print(roots)
在Matlab中,我们有一个名为 fzero 的函数可以解决此问题-不确定Python是否具有类似的功能?
解决方案不必一定要解决-只需处理python论坛用户的建议...
在此先感谢您的协助。真的不知道如果没有stackoverflow我该怎么办!
答案 0 :(得分:0)
您可以按以下步骤更改代码:
from scipy.optimize import fsolve
import numpy as np
f_curve_coefficients = [-7.14285714e-02, 1.96333333e+01, 6.85130952e+03]
S = [0.2122, 0, 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]
f = lambda x : a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)
for N in range(1,6,1):
roots = fsolve(f, 20)
print(roots)
删除功能:
def f(variable):
x = variable
first_eq =a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)
return [first_eq]
并将其转换为:
f = lambda x : a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)
如果您想保留原始代码,请对其进行更正:
def f(variable):
x = variable
first_eq =a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)
return first_eq
您的return [first_eq]
返回列表并生成异常Result from function call is not a proper array of floats.
您还可以按以下方式简化代码:
def f(x):
return a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)
fsolve()
返回f(x)
外观here