Search code examples
pythonarraysarraylistoutputrunge-kutta

The output is list of numbers instead of one number


I ran into the problem, I am new with this kind of usage of Python, I hope some one helps me in this issue. I have a code using RungeKutta algorithm. As I do print(vH), it prints:

[70, 98.72259439054349, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

How could I juts have 98.72259439054349 in out put when I write print(vH)? This is the RungeKutta part of the code and nrk=300. Using nrk we have accurate out put, but with this code as you see we have 300 zeros in output.

def rk4(dH_func, H0, A, B, alpha, b, rho_de0, rho_dm0, z0, z1, nrk):

        if dH_func != False and drho_dm_func != False and drho_de_func != False :
           vH = [0] * (nrk + 1)

           h = (z1 - z0) / float(nrk)
           vH[0] = H = H0

           for i in range(1, nrk + 1):
               k1_H = h * dH_func(z, H, rho_de, rho_dm)

               k2_H = h * dH_func(z + 0.5 * h, H + 0.5 * k1_H, rho_de + 0.5 * k1_rho_de, rho_dm + 0.5 * k1_rho_dm)

               k3_H = h * dH_func(z + 0.5 * h, H + 0.5 * k2_H, rho_de + 0.5 * k2_rho_de, rho_dm + 0.5 * k2_rho_dm)

               k4_H = h * dH_func(z + h, H + k3_H, rho_de + k2_rho_de, rho_dm + k2_rho_dm)

               vH[i] = H = H + (k1_H + k2_H + k2_H + k3_H + k3_H + k4_H) / 6

               return vH

Solution

  • In your function you write:

    for i in range(1, nrk + 1):
        # ...
        return vH
    

    So that means that at the end of the first iteration, you immediately return the result.

    If you want the function to return the result after all the iterations are done, you should write the return vH outside the body of the for loop, like:

    for i in range(1, nrk + 1):
        # ...
    return vH
    

    If you only want to print the second item, you should print it with:

    print(vH[1])