0

I am a Python newbie trying to learn scientific computing, hence some help would be appreciated with this matter. What I am trying to do is to integrate a function when 4 variables take values from given arrays. It works well when only 1 variable is represented by an array, but doesn't work for 4 variables. For example, this works:

    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)

What I am trying to do, but doesn't work:

    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)

I get ValueError: too many values to unpack referring to for loop. I can imagine that the loop has to be expanded to accommodate all arrays, but I am not sure how.

1 Answers1

0

With the for .. in .. loop you can not iterate through multiple lists at once, like you did in your example code. You can use the function zip(...) which returns a list of tuples, where the i-th tuple contains the i-th element from each list, like this:

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)
miindlek
  • 3,523
  • 14
  • 25