首页 > 解决方案 > 用替换求解for循环中的单个(非线性)方程?

问题描述

我正在尝试在 for 循环中使用 fsolve 求解单个(非线性)方程,但是它似乎在我的代码中不起作用。

来自如何在 python 中使用 for 循环求解非线性方程的先前帮助? 我设法解决了两个或多个方程,但无法让它适用于单个非线性方程。

*请注意,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 是否有类似的函数?

解决方案不必是 fsolve - 只需处理来自 python 论坛的用户的建议......

预先感谢您的所有帮助。真的不知道没有stackoverflow我会怎么做!

标签: pythonsolvernonlinear-optimizationequation-solving

解决方案


您可以按如下方式更改代码:

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)

看看lambdas 参考

fsolve()返回此处f(x)查看的根源


推荐阅读