【问题标题】:Solving for a single (non linear) equation in a for loop with substitution?用替换求解for循环中的单个(非线性)方程?
【发布时间】:2020-09-28 20:44:11
【问题描述】:

我正在尝试在 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 是否有类似的函数?

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

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

【问题讨论】:

  • 删除你的函数def f(variable): ... 并改用f = lambda x : a2*x**2+a1*N*x +a0*N**2-(s2*x**2+s1*x+s0)。运行你的代码我得到一个异常,这个改变将解决它。您已经使用来自scipy.optimizefsolve,所以是的,有一个类似的功能。你的问题是什么,你能澄清一下吗?
  • Carlo Zanocco - 感谢您回答我的问题。通过使用 f = lambda 删除 def f(variable) 部分为我解决了它。我将阅读 f = lambda x: ... 不熟悉这个符号。

标签: python solver nonlinear-optimization equation-solving


【解决方案1】:

你可以改变你的代码如下:

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 reference

fsolve() 返回f(x) 的根,看here

【讨论】:

    猜你喜欢
    • 2021-01-13
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    相关资源
    最近更新 更多