Stripers247
Stripers247

Reputation: 2335

Function that computes Runge Kutta not ploting

Hi I am working on a script that will solve and plot an ODE using the Runge Kutta method. I want to have the script use different functions so I can expand upon it later. If I write it with out the function definition it works fine, but with the def() it will not open a plot window or print the results. Than you!

from numpy import *
import matplotlib.pyplot as plt

#H=p^2/2-cosq
#p=dp=-dH/dq
#q=dq=dH/dp

t = 0
h = 0.5
pfa = []                        #Create arrays that will hold pf,qf values
qfa = []

while t < 10:
    q = 1*t
    p = -sin(q*t)

    p1 = p
    q1 = q
    p2 = p + h/2*q1
    q2 = q + h/2*p1
    p3 = p+ h/2*q2
    q3 = q+ h/2*p2
    p4 = p+ h/2*q3
    q4 = q+ h/2*p4
    pf = (p +(h/6.0)*(p1+2*p2+3*p3+p4))
    qf = (q +(h/6.0)*(q1+2*q2+3*q3+q4))

    pfa.append(pf)                   #append arrays
    qfa.append(qf)
    t += h                           #increase time step                        

print("test")
plt.plot(pfa,qfa)
print("test1")
plt.show()
print("tes2t")

Upvotes: 0

Views: 1470

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169434

If you have a function declared, you'll need to call it at some point, e.g.:

def rk(p,q,h):
    pass # your code here

if __name__ == '__main__':
    rk(1,2,1)

Putting the function call within the if __name__ == '__main__' block will ensure that the function is called only when you run the script directly, not when you import it from another script. ( More on that here in case you're interested: What does if __name__ == "__main__": do? )

And here's an even better option; to avoid hard-coding fn args (your real code should have some error-handling for unexpected command-line input):

def rk(p,q,h):
    pass # your code here

if __name__ == '__main__':
    import argparse
    the_parser = argparse.ArgumentParser()
    the_parser.add_argument('integers', type=int, nargs=3)
    args = the_parser.parse_args()
    p,q,h = args.integers
    rk(p,q,h)

Upvotes: 1

Related Questions