Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

Thread: Loop inside a loop won't work

1. Loop inside a loop won't work

I have the following code:

def rk4(f,y0,xInicial,xFinal,N):
i=0
j=0
elementosX=[]
listaNuevaY=[]
distanciaIntervalo=abs(xFinal-xInicial)
if N == 0: #Toda esta parte es escalar
h=distanciaIntervalo
else:
h=distanciaIntervalo/(N)
while xInicial <= xFinal:
elementosX.append(xInicial)
xInicial+=h
for j in range(0,len(f)):
i=0
print(j)
while i < len(elementosX)-1:
if i==0:
listaNuevaY.append(y0[j])
k1=h*f[j](elementosX[i],y0[j])
k2=h*f[j](elementosX[i]+(h/2),y0[j]+(k1/2))
k3=h*f[j](elementosX[i]+(h/2),y0[j]+(k2/2))
k4=h*f[j](elementosX[i]+(h),y0[j]+(k3))
yNuevo=y0[j]+(k1/6)+(k2/3)+(k3/3)+(k4/6)
listaNuevaY.append(yNuevo)
i+=1
else:
k1=h*f[j](elementosX[i],listaNuevaY[i])
k2=h*f[j](elementosX[i]+(h/2),listaNuevaY[i]+(k1/2))
k3=h*f[j](elementosX[i]+(h/2),listaNuevaY[i]+(k2/2))
k4=h*f[j](elementosX[i]+(h),listaNuevaY[i]+(k3))
yNuevo=listaNuevaY[i]+(k1/6)+(k2/3)+(k3/3)+(k4/6)
listaNuevaY.append(yNuevo)
i+=1

The problem I am having is with my variable j, I don't know why it won't go up. My program is only working for j=0 and ending, it won't loop through 0,1,2 or any number. Even though, len(f)=2. I have tried changing the range to (0,2) it won't work neither, j stays at 0 someone knows why?

2. Code:
```def rk4(f,y0,xInicial,xFinal,N):
i=0
j=0
elementosX=[]
listaNuevaY=[]
distanciaIntervalo=abs(xFinal-xInicial)
if N == 0: #Toda esta parte es escalar
h=distanciaIntervalo
else:
h=distanciaIntervalo/(N)
while xInicial <= xFinal:
elementosX.append(xInicial)
xInicial+=h
#print(elementosX)
while j < len(f):
#i=0
#print(j)
while i < len(elementosX)-1:
if i==0:
listaNuevaY.append(y0[j])
k1=h*f[j](elementosX[i],y0[j])
k2=h*f[j](elementosX[i]+(h/2),y0[j]+(k1/2))
k3=h*f[j](elementosX[i]+(h/2),y0[j]+(k2/2))
k4=h*f[j](elementosX[i]+(h),y0[j]+(k3))
yNuevo=y0[j]+(k1/6)+(k2/3)+(k3/3)+(k4/6)
listaNuevaY.append(yNuevo)
i+=1
else:
#print(i)
k1=h*f[j](elementosX[i],listaNuevaY[i])
k2=h*f[j](elementosX[i]+(h/2),listaNuevaY[i]+(k1/2))
k3=h*f[j](elementosX[i]+(h/2),listaNuevaY[i]+(k2/2))
k4=h*f[j](elementosX[i]+(h),listaNuevaY[i]+(k3))
yNuevo=listaNuevaY[i]+(k1/6)+(k2/3)+(k3/3)+(k4/6)
listaNuevaY.append(yNuevo)
i+=1
#j+=1
#print(elementosX)
#print(listaNuevaY)

3. Your function is printing and returning the result inside the loop (at the end of the first iteration) instead of outside the loop (after the loop completes). When it hits the return statement, it ends immediately and returns whatever value it has at that point. Unindent the return statement by one level so that it is not part of the while loop, and it will work.