Note that there are some explanatory texts on larger screens.

plurals
  1. PODefining a global function in a Python script
    primarykey
    data
    text
    <p>I'm new to Python. I am writing a script that will numerically integrate a set of ordinary differential equations using a Runge-Kutta method. Since the Runge-Kutta method is a useful mathematical algorithm, I've put it in its own .py file, rk4.py.</p> <pre><code>def rk4(x,dt): k1=diff(x)*dt k2=diff(x+k1/2)*dt k3=diff(x+k2/2)*dt k4=diff(x+k3)*dt return x+(k1+2*k2+2*k3+k4)/6 </code></pre> <p>The method needs to know the set of equations that the user is working with in order to perform the algorithm, so it calls a function <code>diff(x)</code> that will find give rk4 the derivatives it needs to work. Since the equations will change by use, I want diff() to be defined in the script that will run the particular problem. In this case the problem is the orbit of mercury, so I wrote <code>mercury.py</code>. (This isn't how it will look in the end, but I've simplified it for the sake of figuring out what I'm doing.)</p> <pre><code>from rk4 import rk4 import numpy as np def diff(x): return x def mercury(u0,phi0,dphi): x=np.array([u0,phi0]) dt=2 x=rk4(x,dt) return x mercury(1,1,2) </code></pre> <p>When I run mercury.py, I get an error:</p> <pre><code> File "PATH/mercury.py", line 10, in mercury x=rk4(x,dt) File "PATH/rk4.py", line 2, in rk4 k1=diff(x)*dt NameError: global name 'diff' is not defined </code></pre> <p>I take it since <code>diff()</code> is not a global function, when rk4 runs it knows nothing about diff. Obviously rk4 is a small piece of code and I could just shove it into whatever script I'm using at the time, but I think a Runge-Kutta integrator is a fundamental mathematical tool, just like the array defined in NumPy, and so it makes sense to make it a function that is called rather one that is defined in every script that uses it (which may be many). But I also can't go telling rk4.py to import a particular diff from a particular .py file, because that ruins the generality of rk4 that I want in the first place.</p> <p>Is there a way to define diff globally within a script like mercury.py so that when rk4 is called, it will know about diff?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload