scipy中的多个约束

2024-09-26 18:20:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在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})

Tags: 字符串nameinfortype错误rangescipy
1条回答
网友
1楼 · 发布于 2024-09-26 18:20:35

您可以通过使用evalpython函数绕过这个问题。在这种特殊情况下,它将完全满足您的要求。如果您有一个字符串,并且希望访问具有此名称的函数,只需编写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

相关问题 更多 >

    热门问题