我正在尝试将列表作为输入传递给功能系统。我的功能如下:
beta[i] - (1 - a[i]*beta[i])*(gamma + sum(other betas)
gamma = 0.49
a = [1.57, 2.731, 2.32, 4.681, 1.878]
def g(beta):
return ((beta[0] - (1 - 1.57 * beta[0])*(gamma + np.sum([beta[1], beta[2], beta[3], beta[4]]))),
(beta[1] - (1 - 2.731 * beta[1])*(gamma + np.sum([beta[0], beta[2], beta[3], beta[4]]))),
(beta[2] - (1 - 2.32 * beta[2])*(gamma + np.sum([beta[0], beta[1], beta[3], beta[4]]))),
(beta[3] - (1 - 4.681 * beta[3])*(gamma + np.sum([beta[0], beta[1], beta[2], beta[4]]))),
(beta[4] - (1 - 1.878 * beta[4])*(gamma + np.sum([beta[0], beta[1], beta[2], beta[3]]))),
)
在调用后解决:
optimize.fsolve(g, [1, 1, 1, 1, 1])
答案是:
array([0.46713148, 0.30731229, 0.3502582 , 0.1932526 , 0.41133453]
很明显,对于任意长度的参数,必须有更优雅的方法来执行此操作。我正在尝试以下方法:
def other_betas(lst, index):
return sum(lst)-lst[index]
def temp(beta):
for i in range(len(e)):
beta[i] = (1 - e[i]*beta[i])*(gamma + np.sum(other_betas))
return beta
结尾为:
TypeError: unsupported operand type(s) for +: 'float' and 'function'
答案 0 :(得分:0)
您没有正确调用函数other_betas()
,因为您忘记了方括号,也没有将参数传递给函数。
def other_betas(lst, index):
return sum(lst)-lst[index]
def temp(beta):
for i in range(len(a)):
beta[i] = (1 - a[i]*beta[i])*(gamma + np.sum(other_betas(a, i)))
return beta
print(temp(beta))
但是,您可以对列表进行总结,然后减去for循环中a
的相应元素。使用列表理解,您甚至不需要for循环。
def tempI(beta):
mySum = gamma + np.sum(a)
return [(1 - a[i]*beta[i])*(mySum - a[i]) for i,_ in enumerate(a)]
答案 1 :(得分:0)
您可以通过以下一种功能来实现它:
def g(beta,a):
n = len(a)
summation = [beta[i] - (1 - a[i] * beta[i]) * (gamma + np.sum([beta[j] for j in range(n) if not j==i])) for i in range(n)]
return tuple(summation)
答案 2 :(得分:0)
实际上,两种代码都可以工作:
gamma = 0.49
a = [1.57, 2.731, 2.32, 4.681, 1.878]
def g(beta,n):
lookup = {'0' : 1.57, '1' : 2.731, '2' : 2.32, '3' : 4.681, '4' : 1.878}
summation = [( (1 - lookup[str(i)] * beta[i])) * (gamma + np.sum([beta[j] for j in range(n) if not j==i])) for i in range(n)]
return tuple(summation)
和
def tempI(beta):
mySum = gamma + np.sum(beta)
return [(1 - a[i]*beta[i])*(gamma + np.sum(other_betas(beta, i))) for i,_ in enumerate(a)]
使用以下命令调用函数后:
optimize.fsolve(lambda beta: beta - g(beta, 5), [1, 1, 1, 1, 1])
我们有:
array([0.46713148, 0.30731229, 0.3502582 , 0.1932526 , 0.41133453])