我是一名试图学习科学计算的Python新手,因此可以通过这个问题得到一些帮助。我想要做的是当4个变量从给定数组中获取值时集成一个函数。当只有1个变量由数组表示时,它运行良好,但不适用于4个变量。 例如,这有效:
import scipy.integrate as integrate
from numpy import *
values1 = [3.333, 6.667, 10, 13.333, 16.667, 20] #these are test1 values
test2 = -2.333
test3 = 4.333
test4 = 0.4918
test5 = -12.005
f = lambda u : (u**(test1-1))*((1-u)**test3-test1-1)*((1-u*test4)**-test2)*exp(u*test5)
I=[]
for test1 in values1:
result, err = integrate.quad(f,0,1)
I.append(result)
print(I)
我想做什么,但不起作用:
import scipy.integrate as integrate
from numpy import *
values1 = [3.333, 6.667, 10, 13.333, 16.667, 20] #these are test1 values
values2 = [-2.333, -5.667, -9, -12.333, -15.667, -19] #these are test2 values
values3 = [4.333, 7.667, 11, 14.333, 17.667, 21] #these are test3 values
test4 = 0.4918 #this is constant
values5 = [-12.005, -12.063, -12.121, -12.178, -12.235, -12.293] #these are test5 values
f = lambda u : (u**(test1-1))*((1-u)**test3-test1-1)*((1-u*test4)**-test2)*exp(u*test5)
I=[]
for test1, test2, test3, test5 in values1, values2, values3, values5:
result, err = integrate.quad(f,0,1)
I.append(result)
print(I)
我得到 ValueError:太多值要解压引用for循环。我可以想象循环必须扩展以适应所有阵列,但我不确定如何。
答案 0 :(得分:0)
使用for .. in ..
循环,您无法一次迭代多个列表,就像您在示例代码中所做的那样。
您可以使用返回元组列表的函数zip(...)
,其中第i个元组包含每个列表中的第i个元素,如下所示:
import scipy.integrate as integrate
from numpy import *
values1 = [3.333, 6.667, 10, 13.333, 16.667, 20] #these are test1 values
values2 = [-2.333, -5.667, -9, -12.333, -15.667, -19] #these are test2 values
values3 = [4.333, 7.667, 11, 14.333, 17.667, 21] #these are test3 values
test4 = 0.4918 #this is constant
values5 = [-12.005, -12.063, -12.121, -12.178, -12.235, -12.293] #these are test5 values
f = lambda u : (u**(test1-1))*((1-u)**test3-test1-1)*((1-u*test4)**-test2)*exp(u*test5)
I=[]
for test1, test2, test3, test5 in zip(values1, values2, values3, values5): # Change this line
result, err = integrate.quad(f,0,1)
I.append(result)
print(I)