【问题标题】:Multiple constraints in scipyscipy中的多个约束
【发布时间】:2019-09-26 12:31:44
【问题描述】:

我需要在 scipy 中使用多个约束进行优化:

    cons = ({'type': 'eq', 'fun': cons0},\
         {'type': 'eq', 'fun': cons1},{'type': 'eq', 'fun': cons2}, ....)

我尝试通过循环生成它,但 cons0 或 cons1 或 cons3 被视为字符串,我得到错误。

cons= []

for i in range(3):
     name = cons + str(i)   
     cons.append({'type': 'eq', 'fun': name})

【问题讨论】:

    标签: python scipy scipy-optimize


    【解决方案1】:

    您可以使用eval python 函数绕过此问题。在这种特定情况下,它将完全按照您的意愿行事。如果您有一个字符串并且您想访问具有此名称的函数,只需编写 eval, f.ex eval("cons0")。看例子

    def fun0():
        print "Hey!"
    
    def fun1():
        print "there"
    
    funs = {}
    
    for i in range(0,2):
        funs[i] = eval("fun%d" % i)
    
    print funs
    
    funs[0]()
    funs[1]()
    

    打印出来:

    {0: <function fun0 at 0x7f40ce1ab5f0>, 1: <function fun1 at 0x7f40ce1ab668>}
    Hey!
    there
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-18
      • 2014-07-13
      • 2013-12-03
      • 2019-02-10
      • 2021-12-18
      • 1970-01-01
      • 2016-04-16
      相关资源
      最近更新 更多