【问题标题】:Dynamic equations creation for optimize SciPy fsolve function用于优化 SciPy fsolve 函数的动态方程创建
【发布时间】:2021-10-10 09:14:10
【问题描述】:

我正在使用 scipy 优化函数来求解一些非线性方程。但是我有 11 个方程的变量可以改变,所以我需要为 opt.fsolve 函数创建非线性方程。

我尝试编写一个公式,使用函数创建方程式并将它们存储在列表中。该列表有 11 个方程,形式为 a*b = 2.6, a * k = 4.6, b * g = 3.6, j * b = 1.6 等等。我总共有 11 个这样的方程。

def f(variables) :
 (a,b,c,d,e,f,g,h,i,j,k) = variables
 eq_1=eq_list[0]
 eq_2=eq_list[1] 
 eq_3=eq_list[2] 
 eq_4=eq_list[3] 
 eq_5=eq_list[4] 
 eq_6=eq_list[5] 
 eq_7=eq_list[6] 
 eq_8=eq_list[7] 
 eq_9=eq_list[8]
 eq_10=eq_list[9] 
 eq_11=eq_list[10]
return [eq_1,eq_2 ,eq_3,eq_4 ,eq_5,eq_6,eq_7,eq_8,eq_9,eq_10,eq_11]

solution = opt.fsolve(f, (0.1, 1,1,0.1,1,1,1,1,1,1,1,)) # fsolve(equations, X_0)

但由于这些等式是字符串格式,因此函数会引发异常。
异常“函数调用的结果不是正确的浮点数组。”

我正在尝试使用以下示例

def f(variables) :
 (x,y) = variables
 first_eq = x + y**2 - 4
 print(type(x))
 second_eq = exp(x) + x*y - 3
 return [first_eq, second_eq]
solution = opt.fsolve(f, (0.1, 1)) # fsolve(equations, X_0)  
print(solution)

有没有办法实现我想要做的事情? 动态创建方程式后,我需要使用上述函数。

【问题讨论】:

    标签: python scipy-optimize


    【解决方案1】:

    所以scipy.optimize.fsolve 期望每个方程等于0,所以你需要通过将等号右边的东西向左移动来转换方程。然后你可以解压变量并遍历每个表达式,然后简单地使用eval 来评估它们。所以你可以这样做:

    import scipy.optimize as opt
    from math import exp 
    
    eq_list = ["x + y**2 = 4", "exp(x) + x*y = 3"]
    eq_list_altered = []
    for eq in eq_list:
        start, end = eq.split('=')
        eq_list_altered.append(start + '-' + end)
    
    def f(variables) :
        (x,y) = variables
        res = []
        for eq in eq_list_altered:
            res.append(eval(eq))
        return res
    
    solution = opt.fsolve(f, (0.1, 1))
    print(solution)
    

    请注意,通常不建议使用eval,因为它可以运行任意代码,因此请确保字符串只是来自受信任来源的表达式。更多关于 eval 的安全问题可以找到here

    【讨论】:

      猜你喜欢
      • 2021-02-16
      • 2021-10-14
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-15
      相关资源
      最近更新 更多