简体   繁体   中英

Assigning the last iterated value to a variable in python

I have the last set of values of an iteration: y1[i],y2[i],y3[i] (which was obtained by doing the integration of coupled ODE) Now I need to assign these values to another variables : Y1,Y2,Y3 and then use these variables in a function f(y,t) (ODEs that has to be integrated again). This is part of my code:

#constants used
H = 2.27e-18
l = 1.5
G = 6.637*(10**(-11))
k = (8*3.14*G)**0.5
om_de = 0.75
omega_matter = 1 - om_de
w0 = -0.85
rho_c = 3*(H**2)/(k**2)
c = ((om_de*(1 + w0)*rho_c)/(H**2))**0.5
v0 = (om_de*(1 - w0)*rho_c)/(2*np.exp(-l*k))

#for iteration
p = 0.0
q = 1.0
n = 10000.0

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

dH = (q-p)/n
Y1 = [y1[j]]
Y2 = [y2[j]]
Y3 = [y3[j]]
But I am not able to do any further operations on them.

TypeError: unsupported operand type(s) for ** or pow(): 'function' and 'int'

keeps showing up. The link to the complete code is here: https://pastebin.com/mdQE29N9 (might help in understanding what I am trying to achieve and the code is too lengthy to be posted here)

I think the problem is with the way I have assigned the values,but am not so sure. Any help here as to what is causing this and how I am supposed to solve this would be great.

You have an error in line 57:

def F(Y1,Y2,Y3):
    return Y1*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**(1.0/2.0)

in expression H**2 , where H is defined as a function in line 62:

def H(Y1,Y2,Y3):
    ...

I'm guessing you really meant to say: H(Y1,Y2,Y3)**2 .

But that's not all. Line 52:

y1 == y1.append(y1[j] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))

No need to test for equivalence between y1 and None (that's what append() returns). I'm not sure what you tried to achieve here, maybe this?

y1.append(y1[-1] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))

Also, to access the last element of y1 (line 66), you can use a negative index:

Y1 = [y1[-1]]   # instead of: Y1 = [y1[j]]

You have a variable named H and a function named H()

H = 2.27e-18

and

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

Change the name of the variable or the function for something else.

H_1 = 2.27e-18 #for example

As @randomir says, you probably want to look at his answer too

You can reproduce the error by simple doing:

H = 5

def H(a,b):
  pass

print(H**3)

TypeError: unsupported operand type(s) for ** or pow(): 'function' and 'int'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM